功能模板专业化和Abrahams / Dimov示例 [英] Function template specialization and the Abrahams/Dimov example
问题描述
(我假设您在此问题中了解 Abrahams / Dimov示例。 )
(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)
问题是:
如果我已经给出了上面的声明,那么是可能的对于我现在专门化基本模板1的情况下 T = int *
(例如)?
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)?
或者仅仅声明基本模板2意味着基本模板1不能再被专门化至少对于指针)?
Or does the mere declaration of base template 2 imply that base template 1 can no longer be specialized (at least for pointers)?
推荐答案
您可以通过明确指定模板参数函数名(cf. C ++ 11-Standard 14.7.3)
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;
}
这篇关于功能模板专业化和Abrahams / Dimov示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!