2017-07-27 48 views
-1

我有以下代码:显式调用operator <<的模板超载给出错误

//.hpp 
enum class UIDCategory 
{ 
    GoodType //and others 
}; 
typedef unsigned short UID; 
typedef UID GoodType; 

template<UIDCategory UIDCat> //Yes, UIDCat is supposed to go unused 
inline std::ostream& operator<<(std::ostream& str, const UID& uid) 
{ 
    return str << uid; 
} 

std::ostream& operator<<(std::ostream& str, const Recipe::GoodRatio& goodRatio); 

//definition of Rules here 

template<> 
inline std::ostream& operator<< <UIDCategory::GoodType>(std::ostream& str, const GoodType& goodType) 
{ 
    return str << Rules::goods.at(goodType); 
} 

//.cpp 
std::ostream& operator<<(std::ostream& str, const Recipe::GoodRatio& goodRatio) 
{ 
    return str.template operator<< <UIDCategory::GoodType>(goodRatio.goodType); 
} 

我使用VC++ 17。 我上线以下错误在.cpp文件的功能:

Rules.cpp(21): error C2677: binary '<': no global operator found which takes type 'UIDCategory' (or there is no acceptable conversion) 

我一直在网上搜索了一个解决方案,我发现该template关键字是必要的,调用operator<< <UIDCategory::GoodType>(goodRatio.goodType)到表示operator<<实际上是一个模板,所以我按照所示添加它,但错误不会消失。我在这里做错了什么?

这里的整个想法是为typedef不引入新类型并因此不能在重载解析中使用的限制提供解决方法。当我简单介绍以下超载时,我遇到了麻烦:std::ostream& operator<<(std::ostream& str, const GoodType& goodType)。此标题相当于std::ostream& operator<<(std::ostream& str, const unsigned short& goodType),所以str << aGoodType不明确(与std中的标题冲突)。

我的代码是企图使用户能够明确说明什么< <运营商的“超载”是通过使< <运营商的模板超载,然后明确地专注它的UIDCategory不同成员使用。

我很感激任何关于错误和我试图实现的事情的帮助。

+1

您应该提供[MCVE]。 – Jonas

回答

1

虽然使我的最小,完整和可验证的例子,由乔纳斯建议我实际上解决了这个问题。问题在于我使用了错误的调用约定,运算符是< <。 我把它称为它是流的成员,但它不是。 所以它应该是operator<<<UIDCategory::GoodType>(str, goodRatio.goodType)而不是str.template operator<< <UIDCategory::GoodType>(goodRatio.goodType)

此外,我决定,无论如何,这是我想要实现的方法,并选择了一些简单的方法,但有一些小缺点。