簡體   English   中英

從Typelist創建向量元組

[英]Create tuple of vectors from a Typelist

我有一個簡單的類型列表實現;

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

我想用它來做,是產生std::tuplestd::vector>在每一個類型串式; 例如:

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

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

這就是我一直在玩的:

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

然而,它繼續吐出它期望的類型。 我試過在decltype包裝Ts,就像這樣:

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

但這也是錯的,我猜我也正在使用decltype 那么,我如何基於我拋出的類型列表創建類型向量的元組?

訣竅是使用專門化深入到模板參數。

-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;
}

這是實現你想要的另一種方式。 它依賴於功能的力量:

#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