Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional C++ Class Member Definition

Tags:

c++

class

I'd like to define two variations of a class depending on a template parameter in a C++ class. (I'm using C++17.)

For example, if the template parameter bool flag is true, I'd like the class to have a member:

Class1 foo;

and if flag if false

Class2 bar;

The class definition would also have some logic variation and use either foo or bar. I could implement this using inheritance but I'm exploring if there's another approach. It seems that https://en.cppreference.com/w/cpp/types/conditional may be helpful but I'm not sure. I could also just have both members and just use one of them in any given object, but that seems wasteful and there must be a better way. Note that I don't necessarily need to name the members differently if a particular solution would simply allow me to swap out the class but not the name (perhaps with conditional?).

like image 588
Kulluk007 Avatar asked Mar 19 '26 17:03

Kulluk007


1 Answers

If you can live with the same member name for both versions, then it is trivial:

template <bool flag>
struct Foo {
    std::conditional_t<flag, Class1, Class2> foo;
};
like image 89
Quentin Avatar answered Mar 21 '26 07:03

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!