标签:
std::tuple不支持输入输出,就想实现一下。最初想用模板函数实现,无奈总是不行,就改用模板类了,下面是实现代码。
1 #include <iostream> 2 #include <tuple> 3 using namespace std; 4 5 template <class Tuple, size_t N> 6 struct print_imp 7 { 8 static void print(ostream& out, const Tuple& t) 9 { 10 print_imp<Tuple, N-1>::print(out, t); 11 out << ", " << get<N-1>(t); 12 } 13 }; 14 template <class Tuple> 15 struct print_imp<Tuple, 1> 16 { 17 static void print(ostream& out, const Tuple& t) 18 { 19 out << get<0>(t); 20 } 21 }; 22 template <class... Args> 23 ostream& operator<<(ostream& out, const tuple<Args...>& t) 24 { 25 out << ‘(‘; 26 print_imp<decltype(t), sizeof...(Args)>::print(out, t); 27 return out << ‘)‘; 28 } 29 int main() 30 { 31 auto t = make_tuple(12,4.5,3,6.7,"efa"s); 32 cout << t << endl; 33 }
用模板函数失败的原因是,std::get<INDEX>()里的INDEX必须是编译期常量,而我没有办法通过函数的参数传递一个编译期常量,只好在模板类的模板参数里传递。后来受樱子妹妹启发,不能传常量,就传类型好了。下面的代码使用了一个空类把常量封装成类型:
1 template <size_t N> struct int_{}; 2 3 template <class Tuple, size_t N> 4 void print(ostream& out, const T &t, int_<N>) 5 { 6 print(out,t, int_<N-1>()); 7 out << ", " << get<N-1>(t) ; 8 } 9 10 template <class Tuple> 11 void print(ostream& out, const T &t, int_<1>) 12 { 13 out << get<0>(t); 14 } 15 16 template <class... Args> 17 ostream& operator<<(ostream& out, const tuple<Args...> &t) 18 { 19 out << ‘(‘; 20 print(out,t, int_<sizeof...(Args)>()); 21 return out << ‘)‘; 22 }
不得不说,这份实现清爽了好多,再次感谢樱子妹妹。
标签:
原文地址:http://www.cnblogs.com/lzxskjo/p/4940679.html