Search code examples
c++constructortuples

Tuple of Templated class with different Variadic Arguments


I am trying to construct a tuple of a classes templated with different arguments as below but fails to see how.

template<class T>
struct A
{
    A(T d) : m_t(d) {}

private:
    double m_t;
};

template<class... Ts>
struct B
{
    std::tuple<A<Ts>...> m_tuple;
    
    template<class... Args>
    B(Args&&... args)
    {
        // How can I do:
        // N = number of Args
        // m_tuple = {A<Args[0]>(args[0]), A<Args[1]>(args[1]), ..., A<Args[N]>(args[N])};
    }
};

Solution

  • You can use pack expansion as shown below. Also note that we're using member initializer list to do initialzation of m_tuple instead of assignment inside the ctor body:

    Here we use std::forward:

    template<class... Args>
    B(Args&&... args): m_tuple(std::forward<Args>(args)...)
    {
            
    }