I am wondering if there is a better way to write this for better readability.
If you have a function like below,
void animal(bool hasFourLegs, bool hasHead, bool hasBody);
When you call the function, you will end up with something like
animal(true, false, true);
and this makes me go take a look at the definition every time I encounter function like this.
SO…
I do something like this!
const bool HAS_FOURLEGS = true;
const bool NO_HEAD = false;
const bool HAS_BODY = true;
animal(HAS_FOURLEGS, NO_HEAD, HAS_BODY);
But I do not like to declare const bool
every time I call the function.
It seems like CPP does not support something like
animal(bool hasFourlegs = true, bool hasHead = false, bool hasBody = true);
Is there any better and shorter way?
Best Answer
When I run into issues related to this I sometimes create an
enum
even when there are only 2 expected choices:For example, instead of the following function declaration:
I'd go with:
Therefore, the calling syntax changes from:
to:
Note: this avoids you having to create your own constants every time you call the function.
Edit
As others have suggested, instead of having separate
bool
s for each option and thereby a separateenum
for each it would make sense to have a singleenum
configured as bit flags.