获取表达式的类型(包括引用C++)

Get type of an expression in C++ including references

本文关键字:引用 C++ 包括 表达式 类型 获取      更新时间:2023-10-16

如何获取包含引用的表达式类型?因此,以下伪代码将给出所有 3 次不同的结果。

int a = 5;
std::cout << type(a) << std::endl;
int &b = a;
std::cout << type(b) << std::endl;
int &&c = 5;
std::cout << type(c) << std::endl;

(typeid出于某种原因忽略引用,因此不是一个选项。

如果你只需要看到一个推导的类型,一个技巧是制作一个无法实例化的模板:

template<typename T> struct TD;
TD<decltype(a)> tda;
TD<decltype(b)> tdb;
TD<decltype(c)> tdc;

这将导致编译错误,告诉您a/b/c的类型 .