【问题标题】:Populating a tuple with elements in another tuple用另一个元组中的元素填充一个元组
【发布时间】:2013-07-08 08:49:16
【问题描述】:

在像下面这样的模板中,如何从另一个更复杂的元组中的元素填充一个元组?

template<typename... Ts>
struct foo {
  std::tuple<std::vector<Ts>...> tuple;

  foo() {
    //populate tuple somehow
    //assume that no vector is empty
  }

  void func() {
    std::tuple<Ts...> back_tuple; // = ...
    //want to populate with the last elements ".back()" of each vector
    //how?
  }
};

我找不到任何用于元组的 push_back 机制,所以我不确定如何使用模板循环技巧来做到这一点。此外,我找不到任何类似于模板的 initializer_list 用于不同类型的模板来收集我的值,然后传递到新的元组中。有什么想法吗?

【问题讨论】:

    标签: c++ templates c++11 tuples


    【解决方案1】:

    试试这样的:

    std::tuple<std::vector<Ts>...> t;
    
    template <int...> struct Indices {};
    template <bool> struct BoolType {};
    
    template <int ...I>
    std::tuple<Ts...> back_tuple_aux(BoolType<true>, Indices<I...>)
    {
        return std::make_tuple(std::get<I>(t).back()...);  // !!
    }
    
    template <int ...I>
    std::tuple<Ts...> back_tuple_aux(BoolType<false>, Indices<I...>)
    {
        return back_tuple_aux(BoolType<sizeof...(I) + 1 == sizeof...(Ts)>(),
                              Indices<I..., sizeof...(I)>());
    };
    
    std::tuple<Ts...> back_tuple()
    {
        return back_tuple_aux(BoolType<0 == sizeof...(Ts)>(), Indices<>());
    }
    

    (魔法发生在标记为!!的行中。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多