考虑以下代码
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>
答案 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};
}