I really like the idea of properties in C#, and as a little side project, I\'ve been tinkering with the idea of implementing them in C++. I ran into this example https://sta
Your property is a different object (instance of property<int>
) from the containing object (instance of Foobar
). As such, its member functions get passed a different this
, not the one you'd need to access num_
-- so you can't do it that way. If the lambdas were defined in a non-static member function of Foobar
, they would have captured that function's this
argument and would have had access to the enclosing object's members (explicitly, as this->num_
). But the lambdas are defined in the class, where the non-static data members don't actually exist. If the lambdas did have access to num_
, which num_
, of which instance of Foobar
, would have been that?
The easiest solution that I see is for the property to store a pointer to the enclosing object. That way, it can freely access its non-static members. The downside is that the declaration is slightly more complex (you'd have to do property<int, Foobar> num
) and you'd need to initialize the property by passing the this
pointer. So you won't be able to do it in the class, it would have to be in the constructor's initialization list, hence negating the advantage of C++11's data member initialization.
At that point, this
would be available to the lambdas to capture anyway (by value, not by reference!) so your code would actually work with minimal changes, if you moved the initialization of the property to Foobar's constructor(s):
Foobar::Foobar():
num {
[this]() { return this->num_; },
[this](const int& value) { this->num_ = value; }
}
{
}
Does anyone know whether this
, as passed to whatever constructor happens to be invoked, is available for non-static member initialization in the class definition? I suspect it isn't, but if it were, the same construction would work inside the class definition.