当两者都是operator <<(std::ostream&...
时和通用转换运算符 template<typename T> operator T()
定义为 std::cout << foo();
是模棱两可的。有没有办法让决心调用 operator <<
?
最短的工作代码:
#include<iostream>
struct foo {
int x;
template<typename T> operator T() { return static_cast<T>(x); }
friend std::ostream& operator <<(std::ostream& out, foo& f) { return out << f.x; }
};
//std::ostream& operator <<(std::ostream& out, foo& f) { return out << f.x; } // doesn't help
int main() {
std::cout << foo() << std::endl;
return 0;
}
最佳答案
您自己的运算符不可行,因为它通过临时无法绑定(bind)到的非 const
引用获取 foo
。因此,首先考虑转换后重载。
将其声明更改为
friend std::ostream& operator <<(std::ostream& out, const foo& f) { return out << f.x; }
解决了这个问题。现在您的运算符是更好的匹配,因为它不需要转换。
关于c++ - 如何优先选择 `operator<<` 而不是通用 `operator T()` 转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35565636/