c++ - 将 boost::tuples::cons<...> 转回相应的 boost::tuple<...>

标签 c++ templates boost metaprogramming tuples

对于一个小的图书馆项目,我正在使用 boost::tuple。现在,我面临着将我通过元编程操作的“缺点列表”转回 boost::tuple<...> 类型的问题。 “肮脏”的解决方案是提供大量的部分特化

template<class T> struct id{typedef T type;};

template<class TL> struct type_list_to_tuple_type;

template<class T1>
struct type_list_to_tuple_type<
    boost::tuples::cons<T1,boost::tuples::null_type>
> : id<boost::tuple<T1> > {}

template<class T1, class T2>
struct type_list_to_tuple_type<
    boost::tuples::cons<T1,
    boost::tuples::cons<T2,boost::tuples::null_type> >
> : id<boost::tuple<T1,T2> > {}

template<class T1, class T2, class T3>
struct type_list_to_tuple_type<
    boost::tuples::cons<T1,
    boost::tuples::cons<T2,
    boost::tuples::cons<T3,boost::tuples::null_type> > >
> : id<boost::tuple<T1,T2,T3> > {}

...

但这很乏味且容易出错,尤其是因为我需要支持可能包含许多元素的元组。这些元组类型是通过运算符重载自动生成的。如果可能的话,我想避免写这么多的特化。

关于如何在没有任何 C++0x 功能的情况下做到这一点的想法?我想这是不可能的。但也许我忽略了一些东西。

编辑:我实际上在实验性 C++0x 支持下尝试了这个,结果发现它还不能工作:

template<class TPH>
class type_pack_holder_to_tuple_type;

template<class...Types>
class type_pack_holder_to_tuple_type<
        type_pack_holder<Types...> >
: id< boost::tuple<Types...> > {};

G++ 4.5.1 说:

sorry, unimplemented: cannot expand 'Types ...' into
a fixed-length argument list

:-(

最佳答案

如果您正在进行模板元编程并且需要从类型列表转换为元组,也许您应该考虑使用 Boost.MPLBoost.Fusion .前者提供一组编译时容器和算法来操作时间列表,后者通过提供“混合”容器和算法在纯编译时(MPL)和纯运行时(STL)之间建立联系,可以是可以在编译时通过模板元编程进行操作,也可以在运行时作为元组进行操作。

但是,为了回答您的问题,我认为您不需要将缺点列表转换为元组,因为元组类只是为了更容易地声明元组而提供的便利。事实上,tuple 只是简单地继承了它对应的 cons 列表,例如tuple<int, float>继承自 cons<int, cons<float, null_type> >不添加任何成员数据或功能。所以基本上,当你声明一个 tuple ,库“创建”相应的缺点列表;因为您已经创建了自己的缺点列表,所以您不再需要元组类。

关于c++ - 将 boost::tuples::cons<...> 转回相应的 boost::tuple<...>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4014529/

相关文章:

c++ - QextSerialPort - 检测断开连接

c++ - 如何以线程安全的方式在 openmp 中实现每个进程一次写入全局共享变量?

c++ - 为什么不能覆盖涉及第三方代码的模板类的 operator<<?

c++ - 错误 C2011 : 'member' : 'struct' type redefinition on moving a struct to a new header file

c++ - 在 DLL 项目中使用 Boost (ActiveX)

C++,静态与命名空间与单例

c++ - VS2015 C++ : unable to match function definition to an existing declaration

c++ - 使用模板时如何控制调用哪个函数

c++ - 我可以规定模板类成员仅为 C++03 的原始类型吗?

c++ - 在 boost::python 中公开 boost::scoped_ptr