3 回答

TA貢獻1805條經驗 獲得超9個贊
我在C ++ 11(gcc 4.7)中工作正常。我敢肯定,我沒有考慮過一些陷阱,但是我認為代碼易于閱讀并且并不復雜。唯一奇怪的是可以確保我們在到達最后一個元素時終止的“后衛”結構tuple_printer。另一個奇怪的事情可能是sizeof ...(Types),它返回Types類型包中的類型數。它用于確定最后一個元素的索引(大小...(類型)-1)。
template<typename Type, unsigned N, unsigned Last>
struct tuple_printer {
static void print(std::ostream& out, const Type& value) {
out << std::get<N>(value) << ", ";
tuple_printer<Type, N + 1, Last>::print(out, value);
}
};
template<typename Type, unsigned N>
struct tuple_printer<Type, N, N> {
static void print(std::ostream& out, const Type& value) {
out << std::get<N>(value);
}
};
template<typename... Types>
std::ostream& operator<<(std::ostream& out, const std::tuple<Types...>& value) {
out << "(";
tuple_printer<std::tuple<Types...>, 0, sizeof...(Types) - 1>::print(out, value);
out << ")";
return out;
}
- 3 回答
- 0 關注
- 341 瀏覽
添加回答
舉報