有沒有人試圖創建一組宏來自動創建一個具有任意一組成員變量的類,然後添加對序列化的支持?使用宏使用任意成員變量生成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++如果可能的話解決
有什麼建議嗎?
調試這樣的代碼將是一場噩夢。 – 2014-10-09 21:10:55
也許,但g ++ -E肯定會成爲你的朋友。 – awfulfalafel 2014-10-10 12:37:55