问题描述
尽管使用 auto
关键字进行编程,有时在编译时知道编译器使用的类型有时会很方便。编译是否中止我需要知道类型的位置都没关系。简单示例:
While programming with the auto
keyword it would sometimes be convenient to know the type that is used by the compiler at compile time. It does not matter if the compilation aborts where I need to know the type. Simple example:
std::vector< int > s{1, 2, 3};
for (auto elem : s) {
elem = 5;
}
for (auto elem : s) {
std::cout << elem << std::endl;
}
将打印
1
2
3
因为elem的类型为 int
,而不是 int&
。尝试编译代码并获取 elem
的类型以尽早发现此类错误会很好。
because elem is of type int
, not int&
. It would be nice to try compile the code and get the type of elem
to catch such mistakes early.
推荐答案
经典方法是声明模板结构而无需定义:
Classical way is to declare template structure without definition:
template <typename> struct Debug;
然后使用它:
template struct Debug<std::string>;
或
for (auto elem : s) {
Debug<decltype(elem)>{};
elem = 5;
}
消息错误看起来像
error: explicit instantiation of 'struct Debug<std::__cxx11::basic_string<char> >' before definition of template
template struct Debug<std::string>;
^~~~~~~~~~~~~~~~~~
error: invalid use of incomplete type 'struct Debug<int>'
Debug<decltype(e)>{};
BTW,现在某些IDE在鼠标移至 auto $ c $时显示类型c>或变量。
BTW, now some IDEs show the type when mouse is over auto
or the variable.
这篇关于在编译时获取表达式的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!