Skip to content

Instantly share code, notes, and snippets.

@jbandela
Created December 11, 2012 16:50
Show Gist options
  • Save jbandela/4260214 to your computer and use it in GitHub Desktop.
Save jbandela/4260214 to your computer and use it in GitHub Desktop.
Properties
#include <iostream>
using namespace std;
template<class Class, class Type, const Type& (Class::*Getter)(),void (Class::*Setter)(const Type&)>
class property{
Class* p_;
Class* calc_p(const property& other){
auto diff = reinterpret_cast<const char*>(&other) - reinterpret_cast<const char*>(other.p_);
return reinterpret_cast<Class*>(reinterpret_cast< char*>(this) - diff);
}
public:
property(Class* p):p_(p){}
property(const property& other):p_(calc_p(other)){}
property& operator=(const property& other){
p_ = calc_p(other);
return *this;
}
operator const Type&(){
return (p_->*Getter)();
}
property& operator=(const Type& val){
(p_->*Setter)(val);
return *this;
}
};
struct Test{
const int& get_v(){return v_;}
void set_v(const int& v){v_ = v;}
property<Test,int,&get_v,&set_v> v;
Test():v(this),v_(){}
private:
int v_;
};
//int main(){
// cout << "Hello World\n";
//
// Test t;
// cout << t.v << endl;
// t.v = 5;
// cout << t.v << endl;
// auto t2 = t;
// t2.v = 6;
// cout << t.v << " " << t2.v << endl;
// cin.ignore();
//
//
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment