2014-10-09 104 views
1

有没有人试图创建一组宏来自动创建一个具有任意一组成员变量的类,然后添加对序列化的支持?使用宏使用任意成员变量生成C++类

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

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++如果可能的话解决

有什么建议吗?

+1

调试这样的代码将是一场噩梦。 – 2014-10-09 21:10:55

+0

也许,但g ++ -E肯定会成为你的朋友。 – awfulfalafel 2014-10-10 12:37:55

回答

1

几乎完全符合你想要做的解决方案之一是google protocol buffers。它允许你定义特定格式的结构(IDL),然后生成C++代码(类,序列化等)。

+0

是的,但protobufs使用一个单独的代码生成器。 – dom0 2014-10-09 21:03:56

+0

没错,我也假设你可能会更喜欢自己做:)。我不知道纯粹用C++创建的任何解决方案。 – lisu 2014-10-09 21:07:16