初始化和访问可变类类模板的成员 [英] Initialzing and accessing members of a variadic class template

查看:108
本文介绍了初始化和访问可变类类模板的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

此外,我想能够通过链接构造函数初始化所有成员。这是我到多远:

 模板< 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:在构造函数'Foo< T,Types ...> :: Foo(T,Types ...)':
TestVariadicTemplates.cpp:15:83:error:参数包不用'...'扩展:
TestVariadicTemplates.cpp:15:83:note:'others'
TestVariadicTemplates.cpp:15:困惑的早期错误,bumb out



编辑
$ b

最好的方法是引用 Foo 的各个成员?

解决方案

您必须说明:使用<$ c $展开来自参数包(变量参数)的变量c> ... 。



也就是说,而不是

  Foo   



  Foo< Types ...>(others ...)


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?

解决方案

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... )

这篇关于初始化和访问可变类类模板的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆