模板函数的两个特化(int和int *)。编译错误

时间:2012-01-13 06:56:57

标签: c++ templates template-specialization

template<int* A,int* B>
void f()
{
}
template<int A,int B>
void f()
{
}
void main()
{
    f<(int*)1,(int*)2>();
}

我想要对我的模板f有两个特殊说明。但是这段代码没有编译。有什么问题?

Error   1   error C2440: "specialization" : cannot convert from "int *" to "const int" line 11
Error   2   error C2973: invalid template argument "int *" line 11
Error   3   error C2440: "specialization" : cannot convert from "int *" to "const int" line 11
Error   4   error C2973: invalid template argument "int *" line 11
Error   5   error C2668: 'f' : ambiguous call to overloaded function line 11

编译器Visual C ++ 2010

1 个答案:

答案 0 :(得分:3)

您正在尝试将地址用作模板参数。如果您尝试使用gcc或clang编译代码,则可以使用gcc

test.cpp:11:13: error: a cast to a type other than an integral or enumeration type cannot     appear in a constant-expression
test.cpp:11:21: error: a cast to a type other than an integral or enumeration type cannot appear in a constant-expression

和clang:

candidate template ignored: invalid explicitly-specified argument for template parameter 'A'

这是正确的,根据这个答案:Casting pointer as template argument: Comeau & MSVC compile, GCC fails

也就是说,虽然指针被接受,但它们应该只是指向具有外部链接的命名对象的指针。