Template class initialization vs. Template function initialization


I’m trying to wrap my head around how template specializations differ between classes and functions.

In terms of template classes, here’s a compiling piece of code(c++17, gcc10.2):

template<typename T>
class Student {
    T num;

auto main() -> int {
    Student<int> *t;
    t->num =5;

In terms of template functions, here’s a compiling piece of code (c++17, gcc 10.2):

template<typename T>
T fib(T num) {
    if (num == 1) return 1;
    else if (num == 0) return 0;
    else return fib(num-1) + fib(num-2);

auto main() -> int {
    std::cout << fib(5);
    return 0;

My question is:
Why should I pass in a template-type parameter to instantiate a template class in main whereas I don’t have to do the same for a template function? (For now, ignore that I’ve used a pointer to the template class. The question still stands valid even if the class is instantiated.)

To rephrase the question, I’m trying to understand why is <int> necessary in the main of classes inorder for it to compile, whereas the compiler automatically infers the template-type as <int> in the case of template functions.

I get that template functions provides implicit instantiation at compile time (from the references). However, what’s preventing the compiler from doing the implicit instantiation for classes in the sample piece of code. I believe all necessary information is available at compile time (correct me if I’m wrong here).

Sources I’ve been referring to:



Source: Windows Questions C++