模板函数中的运算符<<:无效操作数
operator<< in template function: invalid operands
我有一个 class Color
,它有 friend std::ostream& operator<<(std::ostream&, Color&)
。它看起来像这样:
struct Color
{
Color(CID c, sstr s)
:color(c),
str(s)
{
}
friend sost& operator<<(sost& o, Color& c)
{
o << "3[1;" << c.color << "m" << c.str << "3[0m";
return o;
}
CID color;
sstr str;
};
我可以在任何情况下毫无问题地调用运算符,但在模板函数中:
template<typename T>
void print_head(const T& head, sost& o)
{
o << head << "\r";
o.flush();
spaces+=(headSize);
}
我用 print_head<helper::Color>(rsym, o);
调用它,rsym
是 Color
的一个实例。我得到
error: invalid operands to binary expression ('sost'
(aka 'basic_ostream<char>') and 'const helper::Color')
o << head << "\r";
~ ^ ~~~~
note: in instantiation of function template specialization
'blk::Bouncer::print_head<helper::Color>' requested here
print_head<helper::Color>(rsym, o);
模板函数有什么问题?
您的运算符采用非 const 引用,但 head
是 const。
你应该把它改成
friend sost& operator<<(sost& o, const Color& c)
我有一个 class Color
,它有 friend std::ostream& operator<<(std::ostream&, Color&)
。它看起来像这样:
struct Color
{
Color(CID c, sstr s)
:color(c),
str(s)
{
}
friend sost& operator<<(sost& o, Color& c)
{
o << "3[1;" << c.color << "m" << c.str << "3[0m";
return o;
}
CID color;
sstr str;
};
我可以在任何情况下毫无问题地调用运算符,但在模板函数中:
template<typename T>
void print_head(const T& head, sost& o)
{
o << head << "\r";
o.flush();
spaces+=(headSize);
}
我用 print_head<helper::Color>(rsym, o);
调用它,rsym
是 Color
的一个实例。我得到
error: invalid operands to binary expression ('sost'
(aka 'basic_ostream<char>') and 'const helper::Color')
o << head << "\r";
~ ^ ~~~~
note: in instantiation of function template specialization
'blk::Bouncer::print_head<helper::Color>' requested here
print_head<helper::Color>(rsym, o);
模板函数有什么问题?
您的运算符采用非 const 引用,但 head
是 const。
你应该把它改成
friend sost& operator<<(sost& o, const Color& c)