, , ++. :
class my_class {
public:
property<int> x;
property<string> y;
...
};
...
my_class obj;
cout << obj.x();
obj.y("Hello, world!");
:
template <typename T, typename U>
struct replace_void {
typedef T type;
};
template <typename T>
struct replace_void<void, T> {
typedef T type;
};
template <typename T, typename D = void>
class property {
typedef typename replace_void<D, property>::type derived_type;
derived_type& derived() { return static_cast<derived_type&>(*this); }
public:
property() {}
explicit property(T const& v) : _v(v) {}
property(property const& p) : _v(p._v) {}
property& operator=(property const& p) { _v = p._v; return *this; }
T operator()() const { return _v; }
void operator()(T const& v) { derived().check(v); _v = v; }
protected:
void check(T const& v) const { (void)v;
private:
T _v;
};
check() - , . :
class nonnegative_int : public property<int, nonnegative_int> {
public:
nonnegative_int(int v) : property<int, nonnegative_int>(v) {}
void check(int const& v) const {
if (v < 0) {
throw "Yikes! A negative integer!";
}
}
};
getter/setter, - !:)
check() a bool, , , . access(), .
EDIT:. - , (, property<int> x x()), , , . , getter/setter .
:. CRTP " ", check() , virtual.