DevShark
DevShark

Reputation: 9112

How can I create an alias for multiple classes in c++

I have two classes A and B defined in a large code base. I'd like to create a type alias that means "A or B". Note that this class will never switch from being an A to being a B during runtime (and vice-versa). How can I do that?

I thought of simply creating an empty class AorB and making A and B both derive from it. However I would much prefer to not have to modify A or B.

I thought of using union, but that seems wasteful from a memory perspective, as this keeps space for the biggest class.

To try and be clearer, here's code to illustrate my question:

class A;
class B;


//typedef AorB = A || B //<- how can I do sthg like that ?

class C {
   AorB myAorB; // once this object is set, it cannot change its underlying type (it stays an A or a B)
};

Upvotes: 2

Views: 288

Answers (1)

lubgr
lubgr

Reputation: 38267

Note that this class will never switch from being an A to being a B during runtime (and vice-versa)

You want to use std::conditional, e.g.

#include <type_traits>

constexpr bool useAOrB() { /* Some actual logic here... */ return true; }

class C {
    std::conditional_t<useAOrB(), A, B> myAorB;
};

Upvotes: 4

Related Questions