AlexDan
AlexDan

Reputation: 3351

difference between member function template of a template class and member function of a template class

CODE 1 :

template <class T>
class cat{
public:
       T a;
       void show(){
       cout << a ;
       }
};

CODE 2 :

template <class T>
class dog{
public:
       T a;
       template <class U> // making show function template
       void show(){
       cout << a ;
       }
};


so cat::show() is a member function of a template class.
and dog::show() is a member function template of a template class.

Questions:
1) is there any difference between class template cat and dog, rather than when I call the member function show, I have to explicitly speciafy U for instance of dog template class?
2) does the compiler handles them the same. for example cat::show() will not be compiled until I use it. and I guess the same thing for dog::show();. so is there anything Im missing here ?

Upvotes: 1

Views: 1125

Answers (1)

Those two are related only in the same way that the two free functions foo are related here:

void foo() {};
template <typename T>
void foo() {}

While being a member of a template class both will be instantiated on demand for implicit instantiations. On the other hand, if you explicitly instantiate the template class, the non-template function will be generated by the compiler, but the template member function will not.

Aside from that, the usual caveats: template functions will only match exact types, while non-template functions will allow implicit conversions:

template <typename T>
struct tmpl {
   void foo( T, T ) {}
   template <typename U>
   void bar( U, U ) {}
};
tmpl<int> t;
t.foo( 5, 1. );    // fine, will convert 1. from double to int
t.bar( 5, 1. );    // error

And all other differences between templated and not templated functions.


What I really don't understand is why this is confusing you so much. It seems that you are considering the instantiation as the only property of functions, which it is not. What is it that really bothers you? Why do you think a template and non-template functions would be the same?

In particular, I feel that you are wasting too much effort into a detail of implementation. In most cases, whether one or all member functions of a template class are instantiated does not really affect the semantics of your program, if your program needs the member function, then the compiler will generate code for it, if your program does not need it, there is no difference whether it generated the code or not (consider that the linker can remove any symbol, what is the difference of the member function never having been generated or it being removed by the linker?)

Upvotes: 1

Related Questions