I was reading this morning the book The Pragmatic Programmer Chapter 3 on Basic Tools every programmer should have and they mentioned Code Generation Tools.
They mentioned one Perl script for C++ programs which helped automate the process of implementing the get/set() member functions for private data members.
Does anyone know about such a script and where to find it? I’ve been unable to come up with the right google keywords to find it.
Although it doesn’t directly answer your question, you may find that generated code is actually unnecessary for managing properties in C++. The following template code will allow you to declare and use properties conveniently:
Here is the code:
check()is a function that tests whether the value being assigned is valid. You can override it in a subclass:There you have it — all of the advantages of externally-generated getter/setter functions, with none of the mess! 🙂
You could choose to have
check()return aboolindicating validity instead of throwing an exception. And you could in principle add a similar method,access(), for catching read references to the property.EDIT: As Mr. Fooz notes in the comments, the class author can later change the implementation without modifying the logical structure of the class (e.g. by replacing the
property<int> xmember with a pair ofx()methods), although binary compatibility is lost so users will need to recompile their client code whenever such a change is made. This ability to painlessly incorporate future changes is actually the main reason people use getter/setter functions instead of public members in the first place.Performance note: Because we are using the CRTP to achieve “compile-time polymorphism”, there is no virtual-call overhead for providing your own
check()in a subclass, and you need not declare itvirtual.