dodo_ind dodo_ind - 1 year ago 53
C++ Question

Does template declaration order matter in c++

The following code is taken from

using namespace std;

template<class T> // (a) a base template
void f( T ){
cout << "base1\n";

template<class T> // (b) a second base template, overloads (a)
void f( T* ){
cout << "base2\n";

template<> // (c) explicit specialization of (b)
void f(int*){
cout << "base3\n";

int main()
int *p = NULL;
f( p );

The output in the above case is "base3". But if I write (c) above (b), the output is "base2". I tested the above code at Can anyone please tell me the reason?

Answer Source

Yes, the order matters here. If you move (c) before (b), then it becomes an explicit specialization of (a) instead of (b).

In overload resolution between the two primary templates, i.e. (a) and (b), (b) is always selected; but (c) is not the specialization of (b) again and then won't be invoked, so you'll get the output "base2".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download