-1

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

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

  • 像结构一样定义,我的意思是逐个字段(没有语法限制),例如像这样的东西。
  • 每个字段类型将是以下类型之一: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”的声明引起的

问候

4

1 回答 1

0

猜测一下您要查找的内容,我有一个快速粗略的示例:

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

演示

于 2015-08-03T18:38:39.833 回答