使用宏的任意成员变量的c++类生成

标签 c++ class templates macros variadic

有没有人试过创建一组宏,自动创建一个具有任意成员变量集的类,然后添加对序列化的支持?

例如,我希望能够编写一个包含如下代码的文件:

GENERATED_CLASS(MyClass)
    GENERATED_CLASS_MEMBER(int, foo);
    GENERATED_CLASS_MEMBER(std::string, bar);
END_GENERATED_CLASS();

GENERATED_CLASS(MySecondClass)
    GENERAGED_CLASS_MEMBER(double, baz);
END_GENERATED_CLASS();

GENERATED_DERIVED_CLASS(MyClass, MyThirdClass)
    GENERATED_CLASS_MEMBER(bool, bat);
END_GENERATED_CLASS();

这有效地导致了

class MyClass
{
public:
    MyClass() {};
    ~MyClass() {};

    void set_foo(int value) { foo = value; }
    void set_bar(std::string value) { bar = value; }
    int get_foo() { return foo; }
    std::string get_bar() { return bar; }

private:
    int foo;
    std::string bar;
};

std::ostream& operator<<(std::ostream& os, const MyClass& obj)
{
    /* automatically generated code to serialize the obj,
     * i.e. foo and bar */
    return os;
}

std::istream& operator>>(std::istream& os, MyClass& obj)
{
    /* automatically generated code to deserialize the obj,
     * i.e. foo and bar */
    return os;
}

class MySecondClass
{
public:
    MySecondClass() {};
    ~MySecondClass() {};

    void set_baz(double value) { baz = value; }
    double get_baz() { return baz; }

private:
    double baz;
};

std::ostream& operator<<(std::ostream& os, const MySecondClass& obj)
{
    /* automatically generated code to serialize the obj,
     * i.e. baz */
    return os;
}

std::istream& operator>>(std::istream& os, MySecondClass& obj)
{
    /* automatically generated code to deserialize the obj,
     * i.e. baz */
    return os;
}

class MyThirdClass : public MyClass
{
public:
    MyThirdClass() {};
    ~MyThirdClass() {};

    void set_bat(bool value) { bat = value; }
    bool get_bat() { return bat; }

private:
    bool bat;
};

std::ostream& operator<<(std::ostream& os, const MyThirdClass& obj)
{
    /* automatically generated code to serialize the obj,
     * i.e. call the << operator for the baseclass,
     * then serialize bat */
    return os;
}

std::istream& operator>>(std::istream& os, MyThirdClass& obj)
{
    /* automatically generated code to deserialize the obj,
     * i.e. call the << operator for the baseclass,
     * then serialize bat */
    return os;
}

由预编译器生成。

我只是不确定执行此操作的最佳方法。如果有人能告诉我如何使用,我不反对使用可变参数模板和可变参数宏,但我非常想避免提升,编写我自己的预处理器,添加任何自定义 makefile 魔法等来实现这一点——一个纯 C++可能的解决方案。

有什么建议吗?

最佳答案

几乎可以完全满足您的需求的解决方案之一是 google protocol buffers .它允许您以特定格式 (IDL) 定义结构,然后生成 C++ 代码(类、序列化等)。

关于使用宏的任意成员变量的c++类生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26287622/

相关文章:

c++ - 如何在 C++ 中实现 resize() 来改变动态成员数据的容量

c++ - 帮助类型特征

c++ - 在 C++ 中用另一个 std::string 替换给定 std::string 的实例

c++ - 用动态内容刷新 wxGrid

c++ - thrust::binary_search 在运行时失败,执行策略指定了用户流

python - 为什么从类和实例中获取属性的查找过程不同?

c++ - 使用 png++ 找出 png 颜色类型

c# - 支持用户定义的数据库字段的动态类

c++ - lambda函数使用其参数作为模板参数调用模板函数

c++ - 错误的模板参数数量(3,应该是 4)