【问题标题】:how to create a complex type using tuples and variadic templates如何使用元组和可变参数模板创建复杂类型
【发布时间】:2015-08-03 17:49:26
【问题描述】:

首先,我不是一个非常熟练的 C++11 和模板程序员,我阅读了很多帖子,但我不知道如何编写我的想法(如果可能的话),我说,这是我的想法。

我的想法是创建一个复杂的编译时类型,我正在尝试遵循这个规则

  • 定义为结构,我的意思是逐个字段(无语法限制),例如 this
  • 每个字段类型都是以下类型之一:int、short、long、byte、bool 和 std::string。
  • 这里是棘手的部分,我想要一个元组,其中每个位置都是对每个字段的引用,这样我可以逐个字段访问存储的数据或获取一个元组。我使用 std::tuples 或 boost::tuples 没有问题。

欢迎任何建议、示例、建议和任何其他评论,我正在努力学习如何做到这一点。

提前致谢

最好的问候

编辑:我可以给你我尝试这样做的代码,也许不是最好的方法,所以我愿意接受建议。

#include <iostream>
#include <tuple>

/* Trait Def */
template<typename T>
struct field_trait
{
    typedef T type;
    typedef type &ref;
    typedef type *pointer;
    typedef const type &const_ref;
};

/* Field Def */
template <typename T>
struct Field : field_trait<Field<T>>
{
    typedef typename T::type value_type;
    typedef typename Field<T>::type field_type;

    typename T::type storage;

    typename T::ref &operator[](const T &c)
    {
        return storage;
    };
};


/* Linear inheritance def */
template<class...Ts>
struct operator_index_inherit {};

template<class T0, class T1, class...Ts>
struct operator_index_inherit<T0, T1, Ts...> : T0, operator_index_inherit<T1, Ts...>
{
  using T0::operator[];
  using operator_index_inherit<T1, Ts...>::operator[];
};

template<class T0>
struct operator_index_inherit<T0>: T0
{
  using T0::operator[];
};

template<class... Fields>
struct bind : operator_index_inherit<Field<Fields>...> 
{
    using base = operator_index_inherit<Field<Fields>...>;
    using base::operator[];

    bind() : data(make_tuple(int(0),string("")))
    {};
    typedef std::tuple<typename Field<Fields>::value_type&... > tuple_t;
    tuple_t data;
};

/* Data type def */
struct t_age : field_trait<int>{};
struct t_name : field_trait<std::string>{};

typedef Field<t_age> age;

int main()
{
    bind<t_age,t_name> data;

    data[t_age()] = 123;
    data[t_name()] = "pepe";

    return 0;
}

这段代码不能编译,错误是声明了类型“tuple_t”和“tuple_t data”引起的

问候

【问题讨论】:

  • 不知道你在问什么。你能提供一个这样的例子吗?
  • 我必须同意巴里的观点:不清楚你在这里问什么。也许提供一个(甚至不工作的)最小样本会让事情变得更容易理解。

标签: c++11 variadic-templates stdtuple boost-tuples


【解决方案1】:

猜测您要查找的内容,我有一个简单粗暴的示例:

#include <iostream>

#include <string>
#include <tuple>

class Type
{
public:
    Type() : t{std::tie(a, b, c, d, e, f)} {}

    int a;
    short b;
    long c;
    unsigned char d;
    bool e;
    std::string f;

    std::tuple<int&, short&, long&, unsigned char&, bool&, std::string&> t;
};

int main()
{
    Type A{};

    A.c = 5;

    std::cout << std::get<2>(A.t) << std::endl;

    return 0;
}

使用demo

【讨论】:

  • 您好 R2,您的示例清晰且功能齐全,但在我的情况下,我无法使用它,因为我需要声明很多此类类,因此需要做很多工作做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多