views:

19

answers:

1

Would it be possible to create a handle ( or a tracking handle ) to a class' property ? For instance,

System::Windows::Forms::CheckBox^ Box = gcnew System::Windows::Forms::CheckBox()

I'd like to create a handle to Box's Checked property and use it to access and modify the same.

+1  A: 

Properties are little more than syntactic sugar for set/get methods, and there is, AFAIK, no way to capture any kind of reference to one (something akin to a bound Method, I suppose).

The best workaround I can think of, which requires VS2010, is to pass a couple of lambdas around:

auto set = [=](bool b) { Box->Checked = b; };
auto get = [=]() -> bool { return Box->Checked; };

EDIT (since you don't have VS2010):

You can of course revert to the rather more baroque convention of writing a special-purpose class:

public generic<typename T> interface class PropertyProxy
{
    property T Field;
};

public ref class CheckBoxChecked : public PropertyProxy<bool>
{
public:
    CheckBoxChecked(System::Windows::Forms::CheckBox^ box) : _box(box) { }
    property bool Field
    {
        bool get() { return _box->Checked; };
        void set(bool b) { _box->Checked = b; };
    }

private:
    System::Windows::Forms::CheckBox^ _box;
};

If anyone ever asks you what C++ lambdas are good for, it's hard to go past this example.

Marcelo Cantos
I see. I'm afraid that isn't an option though. I guess I shall wait for another answer to confirm/contradict yours. Thank you for the quick answer.
shadeMe
Ah, that should help me through the night. Many thanks!
shadeMe