2014-09-27 72 views
1

我寫的元組執行,這似乎工作:不能使用重載運算符<<打印對象的價值

template<typename T, typename... U> 
struct tuple{ 
    T first; 
    tuple<U...> second; 
    tuple()=default; 
    tuple(T t, U... u):first(t), second(u...){} 
    std::ostream& print(std::ostream& stream){ 
     stream<<first<<", "; 
     return second.print(stream); //not using << to avoid extra() in output 
    } 
}; 

template<typename T> 
struct tuple<T>{ 
    T first; 
    tuple()=default; 
    tuple(T t):first(t){} 
    operator T&(){ 
     return first; 
    } 
    std::ostream& print(std::ostream& stream){ 
     return stream<<first; 
    } 
}; 

template<typename... T> 
inline auto mk_tuple(T... t){ 
    return tuple<T...>(t...); 
} 

operator<<重載這樣:

template<typename... T> 
std::ostream& operator<<(std::ostream &stream, tuple<T...> &out){ 
    stream<<'('; 
    return out.print(stream)<<')'; 
} 

當我嘗試使用這種方式:std::cout<<mk_tuple(1, 2, 3, "xyz", 'c');我得到

error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’

然而,mk_tuple(1, 2, 3, "xyz", 'c').print(std::cout)作品。
(但它不令人滿意,因爲它在C++中不是很明顯的語法)。

在這種情況下,我應該如何超載operator<<才能正確使用它?

回答

2

簽名是錯誤的,你需要:

template<typename... T> 
std::ostream& operator<<(std::ostream &stream, const tuple<T...> &out){ 
//            ^^^^^ 

,因爲你不打算修改輸出tuple。這樣可以讓您的操作員使用常量或臨時值進行調用。

它也需要你來標記print方法const

std::ostream& print(std::ostream& stream) const { 
//          ^^^^^ 

一般情況下,谷歌「const正確性」,並瞭解在C++的這一重要範例。


編輯:明白了!試試這個簽名:

template<typename T, typename... U> 
std::ostream& operator<<(std::ostream &stream, const tuple<T, U...> &out){ 
    stream<<'('; 
    return out.print(stream)<<")"; 
} 

一些舊版本的GCC似乎阻止他們正確地推斷只是T...個錯誤。

+0

好點,但它們不會讓代碼編譯。 – GingerPlusPlus 2014-09-27 15:23:41

+0

@GingerPlusPlus我無法讀懂你的思想,所以你必須更具體:在修復操作符和**兩個** print的簽名之後,你得到的錯誤究竟是什麼? – 2014-09-27 15:25:19

+0

'error:can not bind'std :: ostream {aka std :: basic_ostream }'lvalue to'std :: basic_ostream &&''and'/usr/include/c++/4.8/ostream:602:5:error:初始化'std :: basic_ostream <_CharT,_Traits>&std :: operator <<(std :: basic_ostream <_CharT,_Traits> &&,const _Tp&)的參數1 [with _CharT = char; _Traits = std :: char_traits ; _Tp =元組]''[我在線編譯器中的整個代碼](http://rextester.com/live/YZWQ61891) – GingerPlusPlus 2014-09-27 15:30:35