c – 终止函数模板递归
发布时间:2020-12-16 06:48:56 所属栏目:百科 来源:网络整理
导读:我正在尝试为元组创建打印方法.我检查了其他人指定的解决方案,都使用了辅助结构.我不想使用helper struct.我觉得以下代码是有效的,但不能直接得到它. #include iostream#include tr1/tupletemplatetypename tupletype,size_t ivoid print tupletype,0(tuplet
我正在尝试为元组创建打印方法.我检查了其他人指定的解决方案,都使用了辅助结构.我不想使用helper struct.我觉得以下代码是有效的,但不能直接得到它.
#include <iostream> #include <tr1/tuple> template<typename tupletype,size_t i> void print< tupletype,0>(tupletype t)//error: expected initializer before ‘<’ token { std::cout<<std::tr1::get<0><<" "; } template<typename tupletype,size_t i> void print(tupletype t) { std::cout<<std::tr1::get<i><<" ";// no match for 'operator<<' in 'std::cout << get<-78ul>'(my ide actually hangs here!) print<tupletype,i-1>(t); } int main (int argc,char * const argv[]) { std::tr1::tuple<int,float> a(3,5); typedef std::tr1::tuple<int,float> tupletype; print<tupletype,0>(a); } 解决方法
这是没有特定帮助器结构的一个:
#include <iostream> #include <tuple> template<std::size_t> struct int2type{}; template<class Tuple,std::size_t I> void print_imp(Tuple const& t,int2type<I>){ print_imp(t,int2type<I-1>()); std::cout << ' ' << std::get<I>(t); } template<class Tuple> void print_imp(Tuple const& t,int2type<0>){ std::cout << std::get<0>(t); } template<class Tuple> void print(Tuple const& t){ static std::size_t const size = std::tuple_size<Tuple>::value; print_imp(t,int2type<size-1>()); } Live example on Ideone. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |