2016-02-22 48 views
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; 
} 
+0

'operator <<'在那裏甚至是不可行的,因爲'foo()'是一個右值並且'operator <<'需要一個左值參數。 – aschepler

+0

[This code works](http://ideone.com/dbiawM)。 –

回答

3

你自己的操作是不可行的。因此,轉換後過載首先被考慮在內。

改變其聲明

friend std::ostream& operator <<(std::ostream& out, const foo& f) { return out << f.x; } 

修復該問題。現在您的運營商是更好的匹配,因爲它不需要轉換。