Boost logo

Boost :

Subject: Re: [boost] [property] interest in C# like properties for C++?
From: Edward Diener (eldiener_at_[hidden])
Date: 2009-10-20 16:12:54


Peder Holt wrote:
> I have implemented a prototype support for properties in C++.
> It has no space overhead as it manages to deduce the this pointer of the
> class owning it.
>
> Code sample:
>
> #include <boost/static_assert.hpp>
> #include <boost/property.hpp>
> #include <iostream>
>
> class class_with_property {
> public:
> //Implement property template
> template<typename Base>
> class property_with_a_sensible_name : public Base
> {
> public:
> void set(const double& a) {
> //Implement setting of the variable here.
> m_var=a;
> //You can access the owner of the property's this value by
> calling self(), e.g.
> self()->refresh();
> }
> const double& get() const {
> return m_var;
> }
> private:
> double m_var;
> };
> void refresh() {
> std::cout << "Refreshed";
> }
> //Instantiate property template. These can be reused.
>
> BOOST_PROPERTY(class_with_property,property_with_a_sensible_name,property_name);
> };
>
> //And usage:
> void test() {
> class_with_property cls;
> cls.property_name=54.3;
> BOOST_STATIC_ASSERT(sizeof(class_with_property)==sizeof(double));
> }
>
> The trick used is the following:
>
> class my_class {
> public:
> class property_x {
> public:
> my_class* self() {
> //Find offset of member relative to my_class
> size_t offset=size_t(&((my_class*)0)->x);
> //Use this to deduce the address of my_class
> return reinterpret_cast<my_class*>(size_t(this)-offset);
> }
> };
> property_x x;
> };
>
> It currently support:
> Read/Write properties
> Read properties
> Write properties
>
> Not supported yet:
> indexed properties
> operator overloads for properties, e.g. my_class.property*my_class.property
> will currently fail.

Thanks ! Very clever. The self() idea is very worthy, and I may steal it
  for my own idea/implementation about "property" in C++, which I have
been working on indefinitely ( may never get completed to my
satisfaction ). The metaprogramming is breathtaking, if I can slowly
figure it out <g> . In my own implementation a "property" does not need
to be nested class but can exist as a global/static object, so I don't
know how I can use your self() idea but I really appreciate your doing
it and publishing it.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk