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



我在下面的代码中得到一个错误:

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++)

我该如何修复它?

你在这里混合了两种不同的方法。第一个是@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";

最新更新