C++ Template, still able to use class method even not explicit class instantiation

Viewed 45

I have a template class like below.

#include <iostream>
using namespace std;

template <typename T> class Test
{
public:
    void foo(){cout << "foo" <<endl;}
    void goo(){cout << "goo" <<endl;}

    
};

//template class Test<int>; // foo, goo instantiation
template void Test<int>::foo(); //foo instantiation.

int main()
{
    Test<int> t1;
    t1.goo(); 
}

When compile assembly, even exist only foo symbol in there, but above main excutes well without any error and runs ok. I'm wondiring how it executes well.

My understanding of code instantiation by template is generation of the actual code. So expected above is only actual code of foo was generated, but it wasn't.

1 Answers

For templated classes, the compiler instantiates only the methods you actually use.
The "goo" method is probably inlined (you can check that by manual inspection), while the "foo" method is generated probably only because you reference it.

Related