6

Suppose I have:

template <typename T>
class A
{
    //Do something with T
};

I know that the compiler will generate a class A<T> for each different T defined in the code.

What if I have:

class B
{
    template <typename T>
    void f() { /* Do something with T */ }
};

Would there be only one definition of class B but multiple overloads of f() for each different T it's called with?

iammilind
  • 68,093
  • 33
  • 169
  • 336
Shmoopy
  • 5,334
  • 4
  • 36
  • 72
  • 1
    Yes. What else could it be? – Oliver Charlesworth Sep 02 '14 at 08:12
  • 3
    Om Assembly level there is no class definitions. Every class method is compiled to global function with hidden "this" parameter. Templated function is compiled to global function for every instantiated type, in every compilation unit. – Alex F Sep 02 '14 at 08:14
  • Possible duplicate? [Class with templated member function, is the same class?](http://stackoverflow.com/questions/11121910/class-with-templated-member-function-is-the-same-class) – PaperBirdMaster Sep 02 '14 at 08:59

1 Answers1

1

Yes, with every instantiation of f<T> there will be a definition of f() generated by compiler.
Depending on the compiler, the f() could be optimized due to inlining or it can just acquire that much space in the code segment.

However, I have seldom came across this kind of design where you have a non-static template member function (without any argument!) inside a non-template class.

iammilind
  • 68,093
  • 33
  • 169
  • 336