c ++重载流运算符,引用参数和匿名实例

c++ overloading stream operator, parameters by reference and anonymous instances

如果我有一个带有重载流运算符的 POD:

struct Value{
...
    friend ostream& operator<< (ostream &out, Value &val);
...
};

我不能对匿名实例使用流运算符。 例如我不能这样做:

cout<<Value();

这给了我:

error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘Value’)

另一方面,我可以按值传递 POD,但我想避免复制。有办法两者兼得吗?

Value v1;
cout<<v1<<" "<<Value()<<endl;

由于操作符不应该修改右操作数,所以应该const引用:

friend ostream& operator<< (ostream &out, const Value &val);

const 引用可以绑定到临时对象,因此它会起作用(标准库也是这样做的)。