Function template specialization and the Abrahams/Dimov example

不想你离开。 提交于 2019-12-07 04:42:44

问题


(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* *



来源:https://stackoverflow.com/questions/14786008/function-template-specialization-and-the-abrahams-dimov-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!