Function template specialization and Abraham / Dimov example

(I assume the knowledge of the Example of Abraham / Dimov in this matter.)

Suppose there is some third-party code in the header that you cannot change:

template<class T> void f(T);    // (1) base template 1
template<class T> void f(T *);  // (2) base template 2
template<> void f<>(int *);     // (3) specialization of (2)

The question arises:

If I have been given the declarations above as is, is it possible for me now to specialize the basic template 1 for the case when T = int *(for example)?

Or does a simple declaration of base template 2 imply that base template 1 can no longer be specialized (at least for pointers)?

+5
source share
2 answers

You can overload (1) by explicitly specifying the template parameter in square brackets after the function name (see C ++ 11-Standard 14.7.3)

#include <iostream>
using namespace std;
template<class T> void f(T)    // (1) base template 1
{
    cout << "template<class T> void f(T)" << endl;
}

template<class T> void f(T *)  // (2) base template 2
{
    cout << "template<class T> void f(T *)" << endl;
}
//template<> void f<>(int *);     // (3) specialization of (2)

template<> void f<int*>(int *)     // (4) specialization of (1)
{
    cout << "f<int*>(int *)" << endl;
}


int main() {
    int i;
    f(&i); // calls (2) since only base-templates take part in overload resolution
    return 0;
}
+2

, . , . T = int* , . , , no 2 int* *

0

All Articles