2015-06-10 44 views
1

我有一个模板类,具有各种模板功能。其中一个需要超载(几次)。双模板功能过载失败

基本上 - 如果我的课不会是一个模板,这将是我的功能(S):

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; //... 
} 

,我想吃些什么......在
C2768: illegal use of explicit template arguments

C2244: unable to match function definition

1>...\test\main.cpp(74): error C2768: 'OtherClass<MStr>::foo' : illegal use of explicit template arguments 
1>...\test\main.cpp(74): error C2768: 'OtherClass<MStr>::foo' : illegal use of explicit template arguments 
1>...\test\main.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. 

,我一直测试的土地(INT为例)

template<class MStr> 
template<> 
int OtherClass<MStr>::foo<int>(int &t, const MStr &trash) 
{ 
    return t; //... 
} 

欢迎,并在Google和Stackoverflow中寻找数小时......迄今为止最好的答案/问题,似乎并不适用于我this.

问:有没有人能指出我正确的方向,或者有一个解决方案,以解决这个问题?

回答

2

一个回避这个问题的方法是只声明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; //... 
} 

这不,如果特别漂亮你有许多重载情况,但它可能会击败任何其他解决方案。

+0

是的......我已经用'bool'完成了,它不是很漂亮,但我想我会继续这样...然后... – Blacktempel