Apr 29, 2011

C++ Property Template For Eclipse

On Eliminating the Drudgery of Typing

This short, but extremely useful template was inspired from my use of C#. I use ReSharper with VisualStudio and there are even shortcuts for creating auto property types (which are pretty short to begin with). You don't realize how useful  property shortcuts can be, until you get firmly entrenched in the habit of using them, and then you switch IDEs and no longer have them. C++ doesn't have a formal "property" type the way C# does but you often need the same functionality. You have a member variable that you need to expose a getter and setter for.  I actually have three templates named  propfull, propget, and propset. When I need a property I create my member variable first. Then I type prop (ctrl-space) select the template, type the return value and the name of the variable without the prefix. The resulting code doesn't quite fit my coding guidelines so I manually change the first letter of the variable to be lower case. For example, if I invoked the propfull template and type bool  <tab> SomeVariable <enter> I end up with:


and I just type two lower-case letter s characters over the S characters. ( I know all the const qualifiers for bool seems overly pedantic, but that won't be true for all types so it's better to leave them in, plus since I use the lint options for MEC++, it keeps lint happy. )

In the current project, member variables start with m_ (this is the one place I still don't mind using a Hungarian style prefix – it's just so helpful with content assist). If you don't use a prefix and your abhorrence of  Hungarian style borders on zealotry,  feel free to delete the m_ from the template shown below (I may convert someday soon when I can no longer tolerate the ugliness of m_). I set the Context popup in the template editor to C/C++ and I check the Automatically insert checkbox.  If you're new to creating templates, navigation to the proper preferences location is shown below the template.

const ${type} Get${name}() const {return m_${name};}
void Set${name}(const ${type} value){ m_${name} = value;}

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.