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

initializing std::tuple which element constructors require object from another std::tuple

考虑以下代码

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(????...)
   {}

};

如果我需要用 std::get<n>(m_Bs) 初始化 std::get<n>(m_Cs),我应该如何初始化 m_Csm_Cs 中每个元素的构造函数需要来自 [=17= 的相应元素]

How should I initialize m_Cs if I need to initialize std::get<n>(m_Cs) with std::get<n>(m_Bs) i.e. constructor of each element in m_Cs requires a corresponding element from m_Bs

我想你可以在 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};
 }