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.
same_type<decltype(a), decltype(a)>
.
Note that the standard library already has this feature, it's called std::is_same_v<...>
.