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<<
才能正確使用它?
好點,但它們不會讓代碼編譯。 – GingerPlusPlus 2014-09-27 15:23:41
@GingerPlusPlus我無法讀懂你的思想,所以你必須更具體:在修復操作符和**兩個** print的簽名之後,你得到的錯誤究竟是什麼? – 2014-09-27 15:25:19
'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