DeanSinaean
DeanSinaean

Reputation: 2357

TypeA and TypeB are alias to a same primary type, how can they be deduced as different type in C++ template?

I has two different aliased types pointing to a same primary type:

using TypeA = unsigned long
using TypeB = unsigned long

and I am implementing type traits for them. My goal is to deduce different value for them.

template <typename T>
struct LengthTrait {
    constexpr static int size = 5;
};

template<>
struct LengthTrait<TypeA> {
    constexpr  static int size = 4;
};

template<>
struct LengthTrait<TypeB> {
    constexpr  static int size = 8;
};

but compiler tell me TypeA and TypeB are all of type unsigned long so the code can't compile.

My question is: Is there any way to treat TypeA and TypeB differently?

I tried using typedef instead of using, but it didn't work.

Upvotes: 2

Views: 62

Answers (1)

kmdreko
kmdreko

Reputation: 60002

Aliases don't exist as far as the type system goes, they're both unsigned long and nothing else.

The closest thing that I know of is to make them enums:

enum TypeA : unsigned long {};
enum TypeB : unsigned long {};

That way they are unique types and can still be used as integers (with annoyances).

Upvotes: 3

Related Questions