简体   繁体   English

从Typelist创建向量元组

[英]Create tuple of vectors from a Typelist

I have a simple typelist implementation; 我有一个简单的类型列表实现;

template<typename... Ts> 
struct Typelist
{
  static constexpr size_t count{sizeof...(Ts)};
};

What I want to do with it, is for generate an std::tuple of std::vector> for every type in the typelist; 我想用它来做,是产生std::tuplestd::vector>在每一个类型串式; for example: 例如:

struct A {};
struct B {};
struct C {};

using myStructs = typelist<A,B,C>;
using myList = tupleOfVectorTypes<myStructs>; tuple<vector<A>, vector<B>, vector<C>>

This is what I've been playing around with: 这就是我一直在玩的:

template<template<typename... Ts> class T>
struct List
{
  using type = std::tuple<std::vector<Ts>...>;
};

However, it keeps spitting back that it expects a type. 然而,它继续吐出它期望的类型。 I've tried wrapping Ts in decltype , like so: 我试过在decltype包装Ts,就像这样:

using type = std::tuple<std::vector<decltype(Ts)>...>;

But that's wrong as well, and I'm guessing I'm using decltype incorrectly as well. 但这也是错的,我猜我也正在使用decltype So, how can I create a tuple of vectors of types, based off the typelist I throw it? 那么,我如何基于我抛出的类型列表创建类型向量的元组?

The trick is to use specialization to drill down to the template parameters. 诀窍是使用专门化深入到模板参数。

Tested with gcc 5.3.1 in -std=c++1z mode: -std=c++1z模式下使用gcc 5.3.1进行测试:

#include <vector>
#include <tuple>

template<typename... Ts>
struct Typelist{
};

// Declare List
template<class> class List;

// Specialize it, in order to drill down into the template parameters.
template<template<typename...Args> class t, typename ...Ts>
struct List<t<Ts...>> {
    using type = std::tuple<std::vector<Ts>...>;
};

// Sample Typelist

struct A{};
struct B{};
struct C{};

using myStructs = Typelist<A,B,C>;

// And, the tuple of vectors:

List<myStructs>::type my_tuple;

// Proof

int main()
{
    std::vector<A> &a_ref=std::get<0>(my_tuple);
    std::vector<B> &b_ref=std::get<1>(my_tuple);
    std::vector<C> &c_ref=std::get<2>(my_tuple);
    return 0;
}

Here is another way to achieve what you want. 这是实现你想要的另一种方式。 It relies on the power of functions: 它依赖于功能的力量:

#include <cstddef>
#include <tuple>
#include <vector>
#include <utility>

template<typename... Ts> 
struct Typelist
{
  static constexpr size_t count{sizeof...(Ts)};
};

template<class... ARGS>
std::tuple<std::vector<ARGS>... > typelist_helper(Typelist<ARGS...>);

template<class T> 
using vectorOfTuples = decltype(typelist_helper(std::declval<T>()));

struct A{};
struct B{};
struct C{};

using testlist = Typelist<A, B, C>;
vectorOfTuples<testlist> vec;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM