初始化std :: tuple哪些元素构造函数需要来自另一个std :: tuple

时间:2018-08-10 23:58:15

标签: templates c++14 variadic-templates template-meta-programming stdtuple

考虑以下代码

template<typename T> struct B;
template<typename T> struct C;

template<typename...As>
struct A
{
   typedef std::tuple< B<As> ...> Bs;
   typedef std::tuple< C< B<As> >...> Cs;

   Bs m_Bs; 
   Cs m_Cs;

    A() :  
    m_Bs(B<As(someargs)...),
    m_Cs(????...)
   {}

};

如果我需要使用m_Cs初始化std::get<n>(m_Cs)的情况下应该如何初始化std::get<n>(m_Bs),即m_Cs中每个元素的构造函数都需要m_Bs中的相应元素< / p>

1 个答案:

答案 0 :(得分:1)

  

如果我需要使用m_Cs初始化std::get<n>(m_Cs)的情况下应该如何初始化std::get<n>(m_Bs),即m_Cs中每个元素的构造函数都需要m_Bs中的相应元素< / p>

我想您可以在std::index_sequence / std::index_sequence_for的帮助下使用委派构造函数

以下内容

  template <std::size_t ... Is>
  A (std::index_sequence<Is...> const &, As const & ... args)
     : m_Bs{B<As>{args}...}, m_Cs{std::get<Is>(m_Bs)...}
   { }

  A (As const & ... args)
     : A{std::index_sequence_for<As...>{}, args...}
   { }

以下是完整的编译示例

#include <tuple>
#include <type_traits>

template <typename T>
struct B
 { B (T const &) {} };

template <typename T>
struct C
 { C (T const &) {} };

template <typename ... As>
struct A
 {
   private: 
      using Bs = std::tuple<B<As>...>;
      using Cs = std::tuple<C<B<As>>...>;

      Bs m_Bs; 
      Cs m_Cs;

      template <std::size_t ... Is>
      A (std::index_sequence<Is...> const &, As const & ... args)
         : m_Bs{B<As>{args}...}, m_Cs{std::get<Is>(m_Bs)...}
       { }

   public:
      A (As const & ... args)
         : A{std::index_sequence_for<As...>{}, args...}
       { }
 };

int main()
 {
   A<int, long, long long> a{1, 2L, 3LL};
 }