C# has a nice feature called class/struct property. It is a public data member but with the ability to control read/write access, underlying storage or to compute the value on the fly. You can think of it as a glorified getter/setter mechanism: a syntax sugar around get/set methods.

My idea to implement something like this in C++ started few years ago with a code review: a bunch of classes had public data members and no control over who and how they were accessed or modified. I thought to myself: there must be a better way to code it that would appear like public data but, under the hood, gave the author complete control over the variable.

My initial set of requirements was as follows:

  • Access and modification syntax must be indistinguishable from a regular member variable.
  • Access and modification seamlessly routed through user defined get/set methods.
  • The following condition is true: sizeof(T) == sizeof(property<T>).
  • Ability to subscribe to modification events.
  • Ability to bypass the custom get/set methods by explicit syntax only (explicit function call or type cast to the underlying type).
  • Works with primitive and complex types: classes with their own methods defined.
  • Works with arithmetic and bitwise operators.
  • Works with STL containers and smart pointers.

I don’t want to go over the implementation line by line, it’s almost 700 lines of code and growing. But it is useable enough that I feel comfortable sharing it. Here are the language mechanisms I used to make it work:

  • property<T> is a class template that uses policy-based design to specify the get/set control mechanism.
  • The property’s policy class allows for full control over the underlying storage: T can be a member variable or anything else capable of storing values: a file, Windows registry, web resource, etc. Currently member variable and file storage are provided but I’m happy to accept other implementations if you feel like contributing!
  • property<T> relies on concepts heavily to enable or disable member methods and operators.
  • Helper methods are provided such as make_property, strip (gain unrestricted access to the underlying type), and as_volatile.
  • Few template type deduction guides are provided such that creating a property<const char*> results in a property<std::string> and more.
  • Macros help define a whole bunch of member operators as well as standalone unary and binary ones.

P.S. Today’s blog post brought to you by my friend’s one and only NoSpam Android App! Tired of unwanted calls blowing up your phone day and night?! Tired of picking up numbers you don’t recognize and hearing nothing but static?! Don’t wait! Install today and start sending spammers and scammers to /dev/null

Complete source code:
property.hpp | property.cpp



One Reply to “C#-style property in C++”

Leave a Reply