双模板函数重载失败
Double templated function overload fails
我有一个模板类,有各种模板函数。其中一个需要被重载(多次)。
基本上- 如果我的类不是模板,这些将是我的函数:
class OtherClass
{
public:
template<class T> T foo(T &t, const std::string &trash);
};
template<class T>
T OtherClass::foo(T &t, const std::string &trash)
{
return t; //...
}
template<>
std::wstring OtherClass::foo<std::wstring>(std::wstring &w, const std::string &trash)
{
return w; //...
}
:
int main(...)
{
int i = 0;
std::wstring w;
OtherClass o;
i = o.foo(i, std::string(""));
w = o.foo(w, std::string(""));
}
我的模板类看起来像:
template<class MStr>
class OtherClass
{
public:
template<class TVal> TVal foo(TVal &t, const MStr &trash);
};
//Which leads to the function definition
template<class MStr>
template<class TVal>
TVal OtherClass<MStr>::foo(TVal &t, const MStr &trash)
{
return t; //...
}
我想要的……(以int为例)
template<class MStr>
template<>
int OtherClass<MStr>::foo<int>(int &t, const MStr &trash)
{
return t; //...
}
欢迎来到C2768: illegal use of explicit template arguments
和C2244: unable to match function definition
1>...testmain.cpp(74): error C2768: 'OtherClass<MStr>::foo' : illegal use of explicit template arguments
1>...testmain.cpp(74): error C2768: 'OtherClass<MStr>::foo' : illegal use of explicit template arguments
1>...testmain.cpp(74): error C2244: 'OtherClass<MStr>::foo' : unable to match function definition to an existing declaration
1> definition
1> 'int OtherClass<MStr>::foo<int>(int &,const MStr &)'
1> existing declarations
1> 'TVal OtherClass<MStr>::foo(TVal &,const MStr &)'
1>
1>Build FAILED.
我一直在测试,并寻找几个小时在谷歌和Stackoverflow…到目前为止,最好的答案/问题是这样的,但似乎并不适用于我。
问:为了解决这个问题,有没有人可以给我指出正确的方向,或者有一个修复它的方法?
回避这个问题的一个方法是将int
版本声明为重载而不是模板专门化:
template<class MStr>
class OtherClass
{
public:
template<class TVal> TVal foo(TVal &t, const MStr &trash);
int foo(int &t, const MStr &trash);
};
则定义为:
template<class MStr>
int OtherClass<MStr>::foo(int &t, const MStr &trash)
{
return t; //...
}
如果你有很多重载情况,它不是特别漂亮,但它可能胜过任何其他解决方案。
相关文章:
- 使用模板化运算符重载 XOR 运算符失败
- 重载的 operator() 在 Cython 中失败
- ostream_iterator运算符=在pair<int,int>上失败,但在包装器类上工作。我不能为成对<>重载运算符<<吗?
- 在 if 语句中调用重载构造函数失败
- 可变参数模板函数重载失败
- 模板实例化失败:编译器选择不正确的重载函数
- C++ - 在 std::thread 中调用重载函数时编译失败
- 为什么模板参数推导在重载函数时失败?
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- 线性重载:为什么 clang 在 GCC 编译时失败?
- 运算符 == 重载函数失败
- 模板参数扣除失败因运算符重载而失败
- 具有重载<<运算符的简单模板类失败,"Invalid use of template-id"
- 重载乘法运算符失败
- 运算符重载:正常 MSVS,但在 g++ 中失败
- 运算符 << ,>>特定类的重载失败
- 运算符重载失败,运算符[]和运算符强制转换为int
- 只有在其他重载失败时才使用模板重载
- 参数包列表展开导致可变构造函数重载失败
- 双模板函数重载失败