- 如何确保(类)模板的特化实现所有功能?(现在只有当我使用时
mul
才会收到错误消息。) - 对于traits1 / traits2,对int的专业化有什么区别。我认为它们都是模板专业化,但 traits2 不接受
static
并给出链接器错误而不是编译器错误。
.
#include <iostream>
template<typename T>
struct traits1{
static T add(T a, T b) { return a+b; } /* default */
static T mul(T a, T b); /* no default */
};
template<>
struct traits1<int> {
static int add(int a, int b) { return a*b; }
/* static int mul(int a, int b) missing, please warn */
};
template<typename T>
struct traits2{
static T add(T a, T b);
static T mul(T a, T b);
};
template<>
int traits2<int>::add(int a, int b) { return a*b; }
/* traits2<int>::mul(int a, int b) missing, please warn */
int main()
{
std::cout << traits1<int>::add(40, 2) << "\n";
// error: mul is not a member of traits1<int>
//std::cout << traits1<int>::mul(40, 2) << "\n";
std::cout << traits2<int>::add(40, 2) << "\n";
// error: undefined reference to traits2<int>::mul(int, int)
//std::cout << traits2<int>::mul(40, 2) << "\n";
return 0;
}