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.
Post History
There's nothing as elegant as if constexpr, unfortunately. However, it is possible to achieve the practical effects (member functions and data only present conditionally). Start by creating a clas...
Answer
#1: Initial revision
There's nothing as elegant as `if constexpr`, unfortunately. However, it is possible to achieve the practical effects (member functions and data only present conditionally). Start by creating a class template that will encapsulate all the `fooBar`-specific code and data. Use the [Curiously Recurring Template Pattern (CRTP)](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) to make the rest of the `Widget` class accessible: ``` template <class Self> struct Widget_FooBar { void activateFooBar() { fooBar.activate(); self.doSomething(); } private: Self& self() { return static_cast<Self&>(*this); } const Self& self() const { return static_cast<const Self&>(*this); } FooBar fooBar; }; ``` Next, create an empty class to use as an alternative when `FooBar` is not supposed to be used: ``` struct Widget_NoFooBar {}; ``` Finally, choose the appropriate base class for `Widget`: ``` constexpr bool HAS_FOOBAR = whatever; struct Widget : std::conditional_t<HAS_FOOBAR, Widget_FooBar<Widget>, Widget_NoFooBar> { void doSomethingElse() { do_stuff(); if constexpr(HAS_FOOBAR) { activateFooBar(); } } }; ``` This way, the member functions and data are held in `Widget_FooBar`, which is only included in `Widget` if `HAS_FOOBAR` is true.