c++ - 为什么这个函数模板特化不编译?

标签 c++ templates template-specialization

我正在尝试在模板化类中专门化一个模板化函数。在我添加特化之前它工作正常:然后它不再编译。

这是我正在尝试做的事情的简化示例:

template <typename TString, typename TStringStream, typename TChar>
class TestClass
{
public:
    template <typename T>
    static T convert(const TChar* text);
};


//This specialisation doesn't compile
template <typename TString, typename TStringStream, typename TChar>
template <>
inline bool TestClass<TString, TStringStream, TChar>::convert(const TChar* text)
{
    return strcmp(text, "true");
}


template <typename TString, typename TStringStream, typename TChar>
template <typename T>
T TestClass<TString, TStringStream, TChar>::convert(const TChar* text)
{
    TStringStream textStream(text);
    T result;
    textStream >> result;
    return result;
}


void main()
{
    TestClass<RString, RStringstream, char>::convert<bool>("0");
}

这是我尝试编译时 Visual Studio 2010 返回的编译器错误:

error C2244: 'TestClass<TString,TStringStream,TChar>::convert' : unable to match function definition to an existing declaration
    definition
    'bool TestClass<TString,TStringStream,TChar>::convert(const TChar *)'
    existing declarations
    'T TestClass<TString,TStringStream,TChar>::convert(const TChar *)'

我在这里做错了什么?

(这个问题与 this one 不同,因为在该链接中他们试图返回与模板不同的类型,这是一种非常特殊的情况,我在这里不打算这样做。)

最佳答案

[temp.expl.spec]/16 In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well... [ Example:

template <class Y> template <>
void A<Y>::B<double>::mf2() { } // ill-formed; B<double> is specialized but
                                // its enclosing class template A is not

end example ]

基本上,任何以 template<something> template</*nothing*/> 开头的东西格式错误。

关于c++ - 为什么这个函数模板特化不编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32909339/

相关文章:

c++ - 配置文件优化的 C++/C 代码

c++ - 模板容器迭代器

c++ - 在运行时选择合适的专用模板

c++ - 为什么 stringstream 停止接收字符串? [C++]

c++ - 如何验证用户输入的月份输入日期?

c++ - 为进程添加权限

c++ - 在模板类的模板方法中重载 std::function 参数

c++ - 在 C++ 中,我是否需要在关闭程序之前释放内存

c++ - 运算符(operator)填写的模板

c++ - 部分模板类中不允许指向不完整类类型的指针