Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uppercase letter using C++ preprocessor (x -> getX/setX)

I would like to define some properties like:

#define property(T, x) T x; T get ## x (); void set ## x (T value);

class foo { 
public: 
  property(int, count);
  property(float, size);
}

but I would like methods to be called getCount/setCount and not getcount/setcount.

like image 406
Mark Avatar asked Apr 19 '12 14:04

Mark


2 Answers

As the comment says, you cannot do that. Preprocessor doesn't do those kind of things.

So either you follow what @Shahbaz said in the very first comment, or do something like this which gives you get and set of get_count and set_count form.

#define property(T, x) private : T m_## x; \
public : T get_## x () { return m_## x;} \
void set_## x (T value) { m_## x = value; }

class foo { 
public: 
  property(int, count);
  property(float, size);
};

int main() {
        foo f;
        f.set_count(10);
        std::cout << f.get_count() << std::endl;
        return 0;
}

Quick demo at ideone

Note that the variable is declared in the private section and its name is m_count, and the functions are defined (not only declared) in the public section.

Or, you could pass Count instead of count in the macro as:

 property(int, Count);

If you do so, then you could create the variable as m_Count and functions as getCount and setCount. That is closest to what you want.

like image 188
Nawaz Avatar answered Nov 05 '22 16:11

Nawaz


No way (that I know of) to do this using the C pre-processor. I'd suggest as a compromise, you go for an underscore and use get_count() which is easily read. Other alternatives:

  • If you really want to stick with a pre-processor you could investigate using m4 as a first step. It's definitely possible with m4 as I've done something very similar. That said, this seems a bit complicated for what you want to achieve.
  • Add an extra parameter so you get #define property(T, x, name) which allows you to specify the name seperately. It's more flexible but again probably not what you want.
  • If it's really just the legwork of creating the accessors / mutators, there are plenty of IDEs and code generators that will do it for you or you could write some shell / Python / Perl to knock this out as a one off very easily.

Two final observations: Although it might seem more efficient to write it this way, remember that anyone maintaining your code may well do a search for setCount() and not find it which will waste time until they puzzle out what you've done. I.e. from a code maintennce perspective, keep it simple. Secondly, it's good practice to denote macros in upper case, since that way they are easily identified as such. Again this really helps when you're maintaining code.

like image 33
Component 10 Avatar answered Nov 05 '22 17:11

Component 10