循环通过类模板中的元组,插入向量元素

时间:2013-05-05 15:48:23

标签: c++ c++11

问题在于代码:

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

  TupleOfVectorsOfVectors () {
    //Here we already have a tuple of empty vectors.
    //Question: How can I loop through those vectors
    //and push_back into each of them an empty vector?
  }
};

1 个答案:

答案 0 :(得分:4)

您可以在初始化列表中展开参数包。使用统一初始化,我认为这有效:

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

  TupleOfVectorsOfVectors ()
    : tuple { std::vector<std::vector<Ts>> { std::vector<Ts>() }... }
  { }
};

int main()
{
    TupleOfVectorsOfVectors<int, float> t;
    std::cout << std::get<0>(t.tuple).size()
              << std::get<1>(t.tuple).size(); // prints 11, as expected
}

您也可以在成员初始化程序中执行此操作(感谢@JonathanWakely):

template<typename... Ts>
struct TupleOfVectorsOfVectors {
  std::tuple< std::vector<std::vector<Ts>> ... > tuple
     { { std::vector<Ts>() }... }; // mem-initializer

  TupleOfVectorsOfVectors ()
  { }
};