2

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
    `Test t1;` will instantiate the template with `int` – doug Feb 13 '21 at 04:12
  • In general, you only need explicit template instantiation when you want to implement it only in a separate compilation unit. If you place the whole definition in the header then it isn't necessary... – user202729 Feb 13 '21 at 04:46
  • Regarding "why it's not in the assembly (objdump), it's because the function is inlineed. – user202729 Feb 13 '21 at 04:55
  • See also [Can we see the template instantiated code by C++ compiler - Stack Overflow](https://stackoverflow.com/questions/4448094/can-we-see-the-template-instantiated-code-by-c-compiler) – user202729 Feb 13 '21 at 05:32

1 Answers1

3

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.

SimonFarron
  • 242
  • 1
  • 4