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