On a C++ project I got an idea to mix some compile time macro with std::optional to do something like :
#include <optional>
struct Foobar
{
std::optional<int> foo;
std::optional<int> bar;
};
int main()
{
Foobar foobar;
#ifndef DISABLE_FOO
foobar.foo = 42;
#endif // DISABLE_FOO
#ifndef DISABLE_BAR
foobar.bar = 24;
#endif // DISABLE_BAR
//later in the code
if (foobar.foo.has_value())
{
//do some stuff with foo
}
if (foobar.bar.has_value())
{
//do some stuff with bar
}
}
Ideally foo and bar would not be int but more complex structures.
This would ease the readability by not having to use #ifndef
everywhere but for me transforming compile time conditions in runtime conditions like that feels wrong.
Could this be considered bad design (and if yes why?).
if
statements they modify could also just be modified at compile time and potentially save your program a jump, which may matter if the code is performance critical. If the values are modified elsewhere then I have to wonder why the initial values should be different at compile time at all.foo
andbar
.