Suppose you have a function that takes a boolean argument:
void do_something(bool use_some_option);
This has issues because on the call site, you see something like do_something(false) which is not very expressive. If you have multiple such options, it gets worse because the parameters could easily be swapped.
Therefore it is often recommended to use strong types instead of bools, for example an enum class. However, you have to define that enum somewhere and it is also quite cumbersome to use an enum class in conditional statements.
My problem with enum class option : bool { no, yes }; is that you cannot use something like if(use_option){...}.
This problem arises quite often in a large codebase, so it would be nice to have a default way to deal with this issue in a convenient way. My current solution looks like this:
template<typename Name>
class Option {
public:
explicit Option(bool enabled): _enabled(enabled) {}
operator bool() { return _enabled; }
private:
bool _enabled;
};
This can now be used like this:
using UseMyOption = Option<struct UseMyOption_>;
void do_something(UseMyOption use_my_option) {
if(use_my_option) {
...
}
}
Are there any problems with this design for this quite general problem? Are there any issues with an an implicit conversion back to a bool that I am overseeing or is there some further functionality that should be supported?
EDIT:
It seems like the code can be replaced by
enum UseMyOption : bool {};
Is there any behavioral difference to the above implementation? I also wonder why I have never seen a recommendation to use that pattern before because to me this seems to be very useful. Is there any problem with this?