アクセサっぽいもの
#include <iostream> // 特定の型のsetter/getterをかえすmeta function template <class T,class Object> struct accessor_of{ typedef T ( Object::*getter )(); typedef T ( Object::*setter )( const T&); }; // コピーコンストラクタ/=演算子/()演算子を実装した一時オブジェクトをつくる // templateは引数に関数ポインタも受け取れる。 template<class Object, typename T, typename accessor_of<T,Object>::getter GetterFunc, typename accessor_of<T,Object>::setter SetterFunc > class property{ Object *my_object; public: void operator()( Object *obj) { my_object = obj; } T operator()() const { return (my_object->*GetterFunc)(); } T operator()( T const &value) { return (my_object->*SetterFunc)( value ); } T operator =( T const &value) { return (my_object->*SetterFunc)( value ); } operator T() const { return (my_object->*GetterFunc)();} T get() const { return (my_object->*GetterFunc)();} typedef property< Object , T , GetterFunc ,SetterFunc > property_type; }; // 最終的にはマクロを使うw // &とか::はトークンは自己連結するので##は要らない #define attr_of( CLASS , TYPE , NAME) \ property< CLASS , TYPE , &CLASS::get_##NAME ,&CLASS::set_##NAME > NAME // サンプルのクラス class Test { private: int age_; std::string name_; int get_age() { return age_;} int set_age( const int & val ){ return age_ = val ;} std::string get_name(){ return name_;} std::string set_name( const std::string& val){ return name_ = val;} public : // property< Test,int ,&Test::get_age,&Test::set_age > age; attr_of(Test,int,age); attr_of(Test,std::string,name); Test(){ age(this); name(this); } }; int main(){ Test t ; t.age = 10; t.name = "hiroki daichi"; std::cout << t.name() << std::endl; }
ある程度にているコードをパクリながらだったんだけど、結構変なところでハマった。
文法がでかいと難しい。