Kulluk007
Kulluk007

Reputation: 972

Conditional C++ Class Member Definition

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

Upvotes: 2

Views: 1807

Answers (1)

Quentin
Quentin

Reputation: 63124

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;
};

Upvotes: 3

Related Questions