Function template specialization and the Abrahams/

2019-05-02 07:15发布

问题:

(I'm assuming knowledge of the Abrahams/Dimov example in this question.)

Assume there is some 3rd-party code in a header that like this, which you cannot modify:

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 is:

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

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

回答1:

You can overload (1) by explicitly specifying the template parameter in the angle-brackets after the function name (cf. 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:

You could always try and then come to us. But I do not see why it wouldnt work. If T = int* it will work as you want. And hence no 2 would be a parameter of int* *