2
當定義operator <<(std::ostream&...
和通用轉換運算符template<typename T> operator T()
時,std::cout << foo();
不明確。有沒有辦法來調用operator <<
?如何比`運算符'更傾向於`運算符T()`轉換?
最短工作代碼:因爲它通過其暫時不能綁定到非const
裁判採取foo
#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;
}
'operator <<'在那裏甚至是不可行的,因爲'foo()'是一個右值並且'operator <<'需要一個左值參數。 – aschepler
[This code works](http://ideone.com/dbiawM)。 –