类模板状态数据成员,而不是可以显式专门化的实体

时间:2013-01-06 01:41:50

标签: c++ templates visual-c++ template-specialization explicit-specialization

我在下面的代码中遇到错误:

template<typename T, bool B = is_fundamental<T>::value>
class class_name;

template<>
class class_name<string, false>{
public:
    static string const value;
};

template<>
string const class_name<string, false>::value = "Str";
// error: not an entity that can be explicitly specialized.(in VC++)

我该如何解决?

1 个答案:

答案 0 :(得分:5)

您在这里混合了两种不同的方法。第一个是@KerrekSB建议的那个

template<typename T, bool B = is_fundamental<T>::value>
class class_name;

// NOTE: template<> is needed here because this is an explicit specialization of a class template
template<>
class class_name<string, false>{
public:
    static string const value;
};

// NOTE: no template<> here, because this is just a definition of an ordinary class member 
// (i.e. of the class class_name<string, false>)
string const class_name<string, false>::value = "Str";

或者,您可以完整地写出通用类模板并明确专门化<string, false>

的静态成员
template<typename T, bool B = is_fundamental<T>::value>
class class_name {
public:
    static string const value;
};

// NOTE: template<> is needed here because this is an explicit specialization of a class template member
template<>
string const class_name<string, false>::value = "Str";