kyb
kyb

Reputation: 8141

Check if two types are equal in C++

How to check if types are equal in C++11?

 std::uint32_t == unsigned;  //#1

And another snippet

template<typename T> struct A{ 
  string s = T==unsigned ? "unsigned" : "other";
}

Upvotes: 34

Views: 32491

Answers (3)

S.V
S.V

Reputation: 2793

In C++17, one can use:

#include <type_traits>
if constexpr(std::is_same_v<T,U>) { /* do something*/ }

Upvotes: 3

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

For fun, try this:

template<class T>
struct tag_t { using type=T; constexpr tag_t() {}; };
template<class T>
constexpr tag_t<T> tag{};

template<class T, class U>
constexpr std::is_same<T, U>  operator==( tag_t<T>, tag_t<U> ) { return {}; }
template<class T, class U>
constexpr std::integral_constant<bool, !(tag<T> == tag<U>)> operator!=( tag_t<T>, tag_t<U> ) { return {}; }

now you can type tag<T> == tag<unsigned>. The result is both constexpr and encoded in the return type.

live example.

Upvotes: 4

user6420285
user6420285

Reputation:

You can use std::is_same<T,U>::value from C++11 onwards.

Here, T, and U are the types, and value will be true if they are equivalent, and false if they are not.

Note that this is evaluated at compile time.

See http://en.cppreference.com/w/cpp/types/is_same

Upvotes: 42

Related Questions