gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:55:13 24 4
gpt4 key购买 nike

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

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com