« Inside Delegates | Home | Using WolfSSL and cus… »

Xojo like properties with parameters in C++

Xojo has a very unique feature: the assigns keyword. You use it to have two methods (getter and setter) with parameters work like a property. e.g. in the dictionary, you have those methods:

Value(Key as Variant) as Variant

and

Value(Key as Variant, assigns Value 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).

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.

#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;

}

A lot of work for a bit of syntactical sugar. Or do you know a better way in C++? The biggest plugin in space...
29 06 20 - 11:41