property in C++
hi,
I want make property
(http://en.wikipedia.org/wiki/Property_(programming)) in C++.
In the wiki article explained how to make property in C++ using
template mechanism
this looks like
========================================================================
========================================================================
template <typename T> class property {
T value;
public:
T & operator = (const T &i) {
::std::cout << i << ::std::endl;
return value = i;
}
// This template class member function template serves the
purpose to make
// typing more strict. Assignment to this is only possible with
exact identical
// types.
template <typename T2> T2 & operator = (const T2 &i) {
::std::cout << "T2: " << i << ::std::endl;
T2 &guard = value;
throw guard; // Never reached.
}
operator T const & () const {
return value;
}
};
========================================================================
========================================================================
everything is clear (except never reached throw, aprreciate if anybody
explain it to me)
i wish to extend functionality of this property to get addaptable
setting and getting (mechanism) passed to property as template
arguments.
I see it as pointers to member functions.
so i've implemented something:
========================================================================
========================================================================
#include <iostream>
template <typename T, typename C >
class property {
typedef void(C::*PMANIP)( T & i ) ;
mutable T value;
PMANIP _set;
PMANIP _get;
C & _c;
public:
property( C & c, PMANIP set, PMANIP get ): _set(set), _get(get),
_c(c){}
T & operator = (const T &i) {
value = i;
(_c.*_set)(value);
return value;
}
operator T const & () const {
(_c.*_get)(value);
return value;
}
};
struct Foo {
void set( int &i ){ std::cout << "setting " << i << std::endl; }
void get( int &i ){ std::cout << "getting " << i << std::endl; }
property<int, Foo> val;
Foo():val( *this, &Foo::set, &Foo::get ){}
};
int main(int argc, char** argv )
{
Foo foo;
std::cout << "foo.val = " << foo.val << std::endl;
foo.val = 10;
std::cout << "foo.val = " << foo.val << std::endl;
return 0;
}
========================================================================
========================================================================
really nasty cause we need initialize property in !!!EACH!!!
constructor with class instance reference (*this) and pointers to
setter and getter functions.
As far as i understand pointers to setter and getter can be passed as
template parameters.
How to do it?
I can't make typedef in template parameters list to write something
like
template <typename T, typename C, PMANIP Setter, PMANIP Getter>
and anyway i'll need to initialize property with class instance
reference.