c++ - 从 C++11 中的容器元组中提取 value_type 的元组

标签 c++ templates c++11 boost boost-fusion

我有一个带有模板参数的函数,我知道它是一个 std::tuple几个不同元素类型的标准 C++ 容器。 我怎样才能从中提取一个类型 std::tuple元素类型?

例如,假设我有以下功能

template <typename TupOfCtrs>
void doStuff(const TupOfCtrs& tupOfCtrs) {
    using TupOfElements = /*extract a tuple type by applying CtrT::value_type to each container in tupOfCtrs and combining the results into an std::tuple*/;
    MyHelperClass<TupOfElements> helper;
}

我知道它是这样调用的:

std::list<Foo> l {/*...*/};
std::vector<Bar> v {/*...*/};
std::deque<Baz> d {/*...*/};
auto tup = std::make_tuple(l, v, d);

在这种情况下,我想要 TupOfElements助手类型定义为 std::tuple<Foo, Bar, Baz> . 请注意,我不需要实际创建元组,只需获取其类型即可。

如何实现,可能使用 Boost::Fusion图书馆?

最佳答案

您甚至可以在没有 Boost Fusion 的情况下以更简单的方式执行此操作,如下所示:

// Template which takes one type argument:
template <typename Tuple> struct TupOfValueTypes;

// Only provide a definition for this template for std::tuple arguments:
// (i.e. the domain of this template metafunction is any std::tuple)
template <typename ... Ts>
struct TupOfValueTypes<std::tuple<Ts...> > {
    // This definition is only valid, if all types in the tuple have a
    // value_type type member, i.e. the metafunction returns a type only
    // if all types of the members in the std::tuple have a value_type
    // type member, and a std::tuple can be constructed from these:
    using type = std::tuple<typename Ts::value_type...>;
};

template <typename TupOfCtrs>
void doStuff(const TupOfCtrs& tupOfCtrs) {
    using TupOfElements = typename TupOfValueTypes<TupOfCtrs>::type;
    // ...
}

但是为 std::tuple 显式指定 doStuff 当然更容易:

template <typename ... Ts>
void doStuff(const std::tuple<Ts...> & tupOfCtrs) {
    using TupOfElements = std::tuple<typename Ts::value_type...>;
    // ...
}

PS: 另请注意,在许多情况下,如果您只需要一个类型列表,std::tuple 类就有点矫枉过正了,可能会稍微伤害编译时间。就个人而言,我总是使用一个简单的 TypeList 结构:

template <typename ... Ts> struct TypeList
{ using type = TypeList<Ts...>; };

关于c++ - 从 C++11 中的容器元组中提取 value_type 的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35958436/

相关文章:

Django - 一个模板可以扩展两个或多个模板吗?

c++ - 内部类析构函数在基类析构函数之后调用

c++ - 可 move 元素的 vector 会有效地调整大小吗?

c++ - C++11 中的固定长度可变参数包

c++ - 当空指针不是所有位为零时如何正确编写 C/C++ 代码

C++(没有 MFC)禁用/灰色菜单项

C++ 整洁链接器错误

c++ - 将枚举转换为成员变量 [问题] C++

c++ - 引用与模板模板类折叠

javascript - 无法在 Node Express 中查找 Jade View