Adam
Adam

Reputation: 118

C++ Variant of same underlying types

I have a codebase using a std::variant of a few typedefs. Initially, these were different types but now they overlap like the example below

typedef int TA;
typedef int TB;
std::variant<TA, TB> a(TA(1));

Is there a zero-overhead way to make this work? In Scala, I would use opaque types for this purpose, how's something similar achieved C++?

Upvotes: 2

Views: 1055

Answers (1)

eerorika
eerorika

Reputation: 238311

You can wrap the type inside a class:

struct TA {
    int value;
};

struct TB {
    int value;
};

std::variant<TA, TB> a(TA{1});

Now you have two distinct types that each contain an integer with no overhead, and can be distinguished within a variant.


There are some tricks to make a class behave like it was an integer in order to minimise the changes needed in the program. For example, you could define an implicit conversion operator to the underlying type. Such tricks can however be counter-intuitive as well, so use with care.

Upvotes: 2

Related Questions