【问题标题】:Why does this function template specialisation not compile?为什么这个函数模板特化不编译?
【发布时间】:2015-10-02 14:21:40
【问题描述】:

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

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

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 不同,因为在该链接中,他们试图返回与模板不同的类型,这是一种非常特殊的情况,我不想在这里做。)

【问题讨论】:

  • 我的问题有所不同,因为在该链接中,他们试图返回与模板不同的类型,这是一种非常特殊的情况,我不想在这里做。
  • 错了,别这样void main
  • lol 只是为了示例而快速输入,显然这段代码是更大整体的一部分:)

标签: c++ templates template-specialization


【解决方案1】:

[temp.expl.spec]/16 在为类模板的成员或出现在命名空间范围内的成员模板的显式特化声明中,成员模板及其一些封闭类模板可以保持非特化,除非声明不应显式特化类成员模板,如果它的封闭类模板也没有显式特化...... [示例:

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

结束示例 ]

基本上,以template&lt;something&gt; template&lt;/*nothing*/&gt; 开头的任何内容都是格式错误的。

【讨论】:

    【解决方案2】:

    您的源代码不是有效的 C++,template&lt;&gt; 不能遵循模板参数列表。

    模板TestClass&lt;TString, TStringStream, TChar&gt;::convert 也可以完全特化,但仅适用于TestClass&lt;TString, TStringStream, TChar&gt; 的给定实例。如:

    template <>
    template <>
    inline bool TestClass<RString, RStringstream, char>::convert<bool>(const char* text)
    {
        return text == "true";
    }
    

    【讨论】:

    • 如果你需要部分专业化,你必须通过一个类来完成。或者,您可以只做一个重载。
    • 如果是返回值改变而参数保持不变,则重载不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多