5

我正在尝试使用可变参数模板,并想知道是否可以使用它们来概括(?)类模板,例如

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

另外,我希望能够通过链接构造函数来初始化所有成员。这是我已经走了多远:

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;
};

目标是创建这样的对象:

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

代码无法编译(gcc 4.5.3)并出现错误:

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

编辑

引用 的各个成员的最佳方式是Foo什么?

4

1 回答 1

4

你必须按照它说的去做:扩展来自参数包(可变参数)的变量...

也就是说,而不是

Foo<Types ...>( others )

Foo<Types ...>( others... )
于 2012-10-15T21:04:28.443 回答