c++ - 如何使用变量模板比较C++ 17中的变量类型?

标签 c++ types c++14 typeid variable-templates

我有一段漂亮的代码,它使用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.
}

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

有没有办法使这项工作?我本来希望像typeid(x)这样的东西可以解决问题。

最佳答案

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

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

关于c++ - 如何使用变量模板比较C++ 17中的变量类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59445652/

相关文章:

c++ - Windows 8 下 Metro 风格应用程序的类似 Fraps 功能

c++ - C++标准库中的参数类型

c++ - 如何使这段代码更快(学习最佳实践)?

java - Double 数据类型的意外行为

c++ - 为什么从 std::mem_fn 返回的可调用对象可以用于对象和 shared_ptr?

c++ - 参数包递归扩展后`no matching function for call`

c++ - 没有匹配的调用函数,使用函数指针

python - python 中如何检查输入是否为整数?

c++ - 对象具有与成员函数不兼容的类型限定符

c++ - 为什么 std::nullptr_t 在 C++ 中不能与 std::cout 一起使用?