problem implementing getter/setter
Jan 28, 2013 at 6:17am UTC
Hi,
I'm implementing a property class for gui library, just like property in vb
for example
1 2 3 4 5 6 7 8
struct window {
property::rw<string> title;
...
};
window w(...);
w.create(); // displays a new win32 window
w.title = "new title" ; // then the window title is changed
this is the implementation, seems not working
http://liveworkspace.org/code/3zLDWs$4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#include <functional>
#include <iostream>
using namespace std;
namespace property {
template <typename T>
struct value_holder {
T val;
value_holder() : val(T()) {}
};
template <typename T, typename RW>
struct read {
function<T()> getter;
operator T() {
if (getter) return getter();
return ((RW*)this )->val; // how to access value_holder::val
}
};
template <typename T, typename RW>
struct write {
function<void (const T&)> setter;
void operator =(const T& new_val) {
((RW*)this )->val = new_val;
if (setter) setter(new_val);
}
};
// -------- r / w / rw -----------
template <typename T>
struct r
: value_holder<T>
, read<T, r<T>>
{
};
template <typename T>
struct w
: public value_holder<T>
, public write<T, w<T>>
{
using write<T, w<T>>::operator =;
};
template <typename T>
struct rw
: value_holder<T>
, read<T, r<T>>
, write<T, w<T>>
{
using write<T, w<T>>::operator =;
};
}
int main() {
property::rw<int > p;
p = 3; //write access
int x = p; //read access
cout << x << endl;// why output 0
}
Jan 28, 2013 at 7:12am UTC
It was crashing for me when I tried to run it. The problem is you're doing a bad cast.
Specifically, your rw struct is specifying the wrong RW template parameter:
1 2 3 4 5 6 7 8 9
template <typename T>
struct rw
: value_holder<T>
, read<T, /*r<T>*/ rw<T> >
, write<T, /*w<T>*/ rw<T> >
{
using write<T, /*w<T>*/ rw<T>>::operator =;
};
With those changes it works for me.
Jan 28, 2013 at 8:13am UTC
Tanks a lot, what a stupid mistake.
Topic archived. No new replies allowed.