从可变参数模板参数声明成员变量 [英] Declare member variables from variadic template parameter

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

问题描述

很显然,下面的代码无法在C ++中编译。但是我有一种情况,我想基于模板参数对具有零个或多个数据项的类进行参数化。

Obviously the code below doesn't compile in C++. But I have a case where I'd like to parameterize a class with zero or more data items based on template parameters.

有什么方法可以声明一个其数据成员取决于可变参数模板参数,因此我可以访问每个参数?或其他实现我想要的方法?

Is there any way I can declare a class whose data members depend on variadic template parameters so I can access each of them? or some other way to achieve what I'd like?

这是在一个真正的程序中完成的,我已经解决了一种完全不同的方法,但是现在我很感兴趣

This came up in a real program which I've solved an entirely different way but now I'm interested in the more abstract problem of how I might have done this.

template <typename... Types> class Data
{
    // Declare a variable of each type in the parameter pack
    // This is NOT valid C++ and won't compile...
    Types... items;
};

struct Item1
{
    int a;
};

struct Item2
{
    float x, y, z;
};

struct Item3
{
    std::string name;
}

int main()
{
    Data<Item1, Item2> data1;
    Data<Item3> data2;
}


推荐答案

您可以使用 std :: tuple

#include <tuple>

template <typename... Types> class Data
{
    std::tuple<Types...> items;
};

struct Item1
{
    int a;
};

struct Item2
{
    float x, y, z;
};

struct Item3
{
    std::string name;
};

int main()
{
    Data<Item1, Item2> data1;
    Data<Item3> data2;
}

尝试一下此处

这篇关于从可变参数模板参数声明成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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