1

I have this beautiful piece of code, which is using C++14s variable templates:

#include <typeinfo>

template<typename T, typename U> 
constexpr bool same_type = false; 

template<typename T> 
constexpr bool same_type<T,T> = true; 

int main() {
    bool f = same_type<int, bool>; // compiles. Evals to false.
    bool t = same_type<int, int>; // compiles. Evals to true.
    int a; 
    int b;
    return same_type<typeid(a), typeid(a)>; // does not compile.
}

It checks if two types are the same. I like this, but it seems quite useless to me if I have to pass in the types myself, instead of deriving them from some variables.

Is there a way to make this work? I would have expected that something like typeid(x) might to the trick.

User12547645
  • 6,955
  • 3
  • 38
  • 69

1 Answers1

4

same_type<decltype(a), decltype(a)>.

Note that the standard library already has this feature, it's called std::is_same_v<...>.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207