我有以下代码:
//.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
中的标题冲突)。
我的代码试图让用户明确说明&lt;&lt;&lt;&lt;&lt;运算符是通过对&lt;&lt;&lt;&lt;&lt;&lt;运算符,然后明确地将其专门用于UIDCategory
的不同成员。
我很感激任何关于错误和我想要实现的事情的帮助。
答案 0 :(得分:1)
在制作Jonas建议的Minimal,Complete和Verifiable示例时,我实际上解决了这个问题。问题是我使用了错误的调用约定&lt;&lt;运营商。
我把它称为流,但它不是流的成员。
因此它应该是operator<<<UIDCategory::GoodType>(str, goodRatio.goodType)
而不是str.template operator<< <UIDCategory::GoodType>(goodRatio.goodType)
。
此外,我认为这无论如何都是为了实现我想要实现的目标,并选择了一种带有一些小缺点的简单方法。