Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

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

66%
+2 −0
Q&A Can I conditionally include class members without using #ifdef?

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...

posted 6mo ago by Angew‭

Answer
#1: Initial revision by user avatar Angew‭ · 2024-05-09T09:57:47Z (6 months ago)
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.