Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Can I conditionally include class members without using #ifdef?
Post
Can I conditionally include class members without using #ifdef?
#ifdef
sections can, of course, be used to include or exclude chunks of code based on some criteria known at compile time. One big problem is that when the condition is evaluated to false
, the chunk is not only excluded from the compiled code but the compiler skips right over it altogether. This means code in that skipped chunk won't go through the compiler's checks to determine whether it's still valid.
For the contents of a function, it's possible to get the best of both worlds using if constexpr
. If it evaluates to false the compiler will exclude the body of the statement, but will still check that it's valid.
Is there any way to do this with member variables, though?
Say I have a Widget
class that may or may not need a FooBar
depending on whether or not we want that feature in one of the many products that uses Widget
. I can do this:
class Widget
{
public:
Widget();
void doSomething();
void doSomethingElse();
#ifdef HAS_FOOBAR
void activateFooBar();
#endif
private:
#ifdef HAS_FOOBAR
FooBar fooBar;
#endif
};
The advantage is that when I'm building the code for a product that doesn't have a FooBar, my Widget
class doesn't have methods it doesn't need, and will also take up less memory due to the member variable being gone. But the disadvantage is that if I'm working on something for a product that doesn't have a FooBar, if I make a change that would break the code in activateFooBar
I might miss it entirely until the next time someone builds for a product that does have a FooBar.
If HAS_FOOBAR
were a constexpr bool
, instead of excluding activateFooBar
I could maybe implement it like this:
void Widget::activateFooBar()
{
if constexpr (!HAS_FOOBAR)
return;
// ...
}
but then I still have the fooBar
member, no matter what, and instances of the Widget
class will always include it in the memory they take up.
Is there any nice, neat way to avoid this?
1 comment thread