Home > Software engineering >  Comping if two types are "literally" the same
Comping if two types are "literally" the same

Time:05-30

Let's say we have two types

using t1 = int*; using t2 = int*;

I know that std::is_same<t1, t2>::value will give us true. And what is, or, is there a template tool to achieve the following?

tool<t1, t2>::value == false;
tool<t1, t1>::value == true;

I'd say it's probably impossible but I am not an expert in C .

Presumably, this tool can be used in a template function as

using allowed = int*;
using not_allowed = int*;

template <class T>
void f(T var) {
   static_assert(tool<T, allowed>::value &&
                 tool<T, not_allowed>::value == false, "");
}

Thanks!

CodePudding user response:

No, there isn't. t1 and t2 are literally the same type. using does not introduce any new types. It simply gives an alias name to an already existing type.

If you want a distinct, but otherwise identical, "copy" of a type, you need to create a new class and implement the interface of the original type in the new class. (Inheritance may help, but not when the "copied" type is a non-class type like here. In the case of lambdas, you could simply repeat the lambda a second time to achieve this.)

There is currently no way to create a distinct "copy" of an arbitrary type, i.e. a strong typedef. The new type must be implemented explicitly. (Searching for strong typedef should give you some examples and libraries helping to implement it.)

CodePudding user response:

You often want something like this so you can differentiate semantically different values that happen to have the same type. A way of doing that in C would be to have a thin layer of struct-wrapping around them.

struct Litre {
    int value;
};

struct Metre {
    int value;
};

// Maybe also define operators that make sense

void foo(Metre* pm) {
    // won't work with Litre*
}
  •  Tags:  
  • c
  • Related