asmbaty
asmbaty

Reputation: 516

How to tell if two variables have the same type at compile time?

Is there a better way (or another way) to tell if two variables have the same type at compile time than this:

auto var1 = ..;
auto var2 = ..;
static_assert(std::is_same<decltype(var1), decltype(var2)>::value);

Upvotes: 2

Views: 2373

Answers (3)

Pete Becker
Pete Becker

Reputation: 76523

It's not completely clear what the actual problem is here, but the simplest way to make sure that two variables have the same type is to write them that way:

int var1 = /* whatever */;
int var2 = /* whatever */; // var1 and var2 have the same type

if you're a fan of auto instead of writing the actual type, you can write code that simply defines the second variable with the same type as the first:

auto var1 = /* whatever */;
decltype(var1) var2 = /* whatever */; // var1 and var2 have the same type

another possibility is to write a template function that takes two arguments of the same type:

template <class Ty> void f(Ty var1, Ty var2) { /* do something */ }
f(var1_expression, var2_expression);

if the types of var1_expression and var2_expression are not the same the template instantation will fail.

Upvotes: 0

gsamaras
gsamaras

Reputation: 73444

Is there a better way to tell if two variables has the same type at compile time?

No, std::is_same is the way to go. You could use of course std::is_same_v, as @L.F. commented, but that's basically the same philosophy.

Is there another way to tell if two variables has the same type at compile time?

Yes, as shown in this answer.

Upvotes: 0

Andreas DM
Andreas DM

Reputation: 11028

Is there a better way (or another way) to tell if two variables has the same type at compile time than this:

Well, you can use the helper variable template std::is_same_v

template< class T, class U >
inline constexpr bool is_same_v = is_same<T, U>::value;

then it'll become

static_assert(std::is_same_v<decltype(var1), decltype(var2)>);

Upvotes: 1

Related Questions