[英]How to use variable templates to compare the types of variables in C++ 17?
我有这段漂亮的代码,它使用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)
类的东西可能会奏效。
same_type<decltype(a), decltype(a)>
。
请注意,标准库已经具有此功能,称为std::is_same_v<...>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.