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.
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.
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:
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.#define property(T, x, name)
which allows you to specify the name seperately. It's more flexible but again probably not what you want.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With