1

我有这段漂亮的代码,它使用C++14s 变量模板

#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.
}

它检查两种类型是否相同。我喜欢这个,但是如果我必须自己传递类型而不是从某些变量中派生它们,这对我来说似乎毫无用处。

有没有办法使这项工作?我本以为会有这样typeid(x)的伎俩。

4

1 回答 1

4

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

请注意,标准库已经具有此功能,称为std::is_same_v<...>.

于 2019-12-22T15:45:41.967 回答