The short version: propertypp on GitHub
The long version:
A co-worker recently told me he had made some member variables in a C++ class public, because a getter and setter for them would just do exactly the same thing as reading and writing those member variables directly. I told him that was bad design, and he told me he was aware of it but that in that particular case making those member variables public would hardly have any negative impact on the system, because it was a small piece of code with a very limited and controlled scope. I told him he should still consider making those member variables private and writing getters and setters, but then he admitted he found the get*() and set*() syntax too cumbersome.
I agree with him on that last point. Calling getters and setters makes code so ugly when you could be using dot notation. Objective-C and other languages have this nice little feature called properties, which allow you to use dot notation for accessing member variables of a class, but having getters and setters getting called behind the scenes.
I began wondering if it would be possible to implement properties in C++ and soon realized it is, indeed, possible. You can declare public member variables of wrapper classes that overload cast and assignment operators and read and write private member variables containing property values. If that explanation wasn’t enough to help you picture the solution, here are some example implementations:
http://www.cplusplus.com/forum/general/8147/
http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4031
Those aren’t the only C++ property implementations available out there, but I found that all implementations required too much code to be used.
I set out to write a generic C++ property library that required as little effort to be used by the programmer as possible. propertypp is the result of that. I wont’t go into detail here on how to use it and what code that uses it looks like, because it’s all there on the README on GitHub.
Notice how I’ve managed to have the name of the class containing the properties to be informed only on getter and setter synthetization. If you read the code on propertypp.h
, you’ll see there was no way out of that. Another nice thing is that it doesn’t have any dependencies on third-party libraries: it’s just plain C++ and STL. My initial, unpublished implementation used Boost.Function to wrap the function objects for getters and setters, but I didn’t want to impose that dependency on every project that shall use propertypp.
propertypp is far from finished. At present, it only works with fundamental data types and pointers. That prevents having a struct or object as a property, unless it’s a pointer to that struct or object. I also want to support read-only properties.
I have to admit I’m quite proud of my work on propertypp. So far, the people I’ve shown it to thought it nice. However, criticism will be appreciated if anyone has any 🙂