Xojo like properties with parameters in C++
andValue(Key as Variant) as Variant
The first is a normal method returning the result. But the second one has an extra parameter, which is then filled with an assign operation. You write something like d.value(1) = 2, where the 2 is internally put as a parameter and internally calls Value(1,2).Value(Key as Variant, assigns Value as Variant)
To replicate this in C++, we got a way to replicate this by using a temporary object and two blocks for getter and setter. So the value() function in C++ returns the IntPropertyAssign object, which knows how to get or set the value. Then we can either assign a value, which calls to the operator= and calls setter. If you query the value, it calls through to the getter.
A lot of work for a bit of syntactical sugar. Or do you know a better way in C++?#include <iostream>
typedef void (^IntPropertySetter)(int value);
typedef int (^IntPropertyGetter)();
class IntPropertyAssign
{
IntPropertySetter setter;
IntPropertyGetter getter;
public:
IntPropertyAssign(IntPropertyGetter g, IntPropertySetter s) { setter = s; getter = g; }
IntPropertyAssign(const IntPropertyAssign &other) : setter(other.setter), getter(other.getter) { }
IntPropertyAssign& operator= (int v) { setter(v); return *this; }
operator int () { return getter(); };
};
class MyTest {
int values[10];
public:
MyTest()
{
memset(&values, 0, sizeof(values));
}
IntPropertyAssign value(int index)
{
IntPropertyGetter g = ^{ return values[index]; };
IntPropertySetter s = ^(int v){ values[index] = v; };
IntPropertyAssign v(g,s);
return v;
}
};
int main(int argc, const char * argv[]) {
MyTest t;
t.value(2) = 3;
int v = t.value(2);
std::cout << "value: " << v;
return 0;
}