类模板的成员或成员模板可以明确专门用于类模板的给定隐式实例化...
经过一些测试,我发现专门化应该与类模板的隐式实例化中的成员匹配,这意味着它们应该是相同的类型 . 例如,
template<class T> struct A {
void f(T);
static T i;
};
template<> void A<int>::f(int); // ok
// template<> void A<int>::f(char); // error
template<> int A<int>::i; // ok
// template<> char A<int>::i; // error
Where does the standard specify such constraints?
2 回答
正如Evgeny的评论所指出的那样:
为
int
类型实例化struct A
,您将获得一个定义的方法void f(int);
.如果要实现
template<> void A<int>::f(char) { }
-struct A<int>
中没有定义此类方法 .为了达到这个目的,你可以将整个
struct A
专门用于int
.另一种方法是(如answer of user846834中所示)使quest中的方法成为模板本身 .
示例代码:
输出:
在coliru现场演示
在您给出的链接示例中,只有非类型模板参数(
X1, X2
)被指定为与T不同的类型 . 并且只能将它们指定为不同 . 类型模板参数需要与特化相同 .