Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialzing and accessing members of a variadic class template

I'm experimenting with variadic templates and would like to know if they can be used in order to generalze(?) class templates such as

template<typename T1, typename T2 , typename T4, typename T4>
struct Foo
{
    T1      &m_member1;
    T2      &m_member2;
    T3      &m_member3;
    T4      &m_member4;
};

Also, I'd like to be able to initialize all the members by chaining constructors. This is how far I've gotten:

template<typename... Types>
struct Foo;

template<typename T , typename... Types>
struct Foo<T, Types ...> : public Foo<Types ...>
{
    Foo( T member , Types ... others ) : m_member( member ) , Foo<Types ...>( others )
    {
    }

    T   m_member;
};

template<typename T>
struct Foo<T>
{
    Foo( T member ) : m_member( member )
    {
    }

    T   m_member;
};

Where the goal is to create objects like so:

Foo<char,int,bool,float> f( 'a' , 42 , true , 1.234 );

The code fails to compile (gcc 4.5.3) with the error:

TestVariadicTemplates.cpp: In constructor ‘Foo<T, Types ...>::Foo(T, Types ...)’:
TestVariadicTemplates.cpp:15:83: error: parameter packs not expanded with ‘...’:
TestVariadicTemplates.cpp:15:83: note:         ‘others’
TestVariadicTemplates.cpp:15: confused by earlier errors, bailing out

Edit

What would be the best way to reference the various members of Foo?

like image 545
Olumide Avatar asked Oct 06 '22 07:10

Olumide


1 Answers

You have to do what it says: Expand the variables that come from Parameter packs (variadic parameters) with ....

That is, instead of

Foo<Types ...>( others )

write

Foo<Types ...>( others... )
like image 184
bitmask Avatar answered Oct 10 '22 04:10

bitmask