在编译时获取表达式

hoc*_*chl 0 c++ c++11 c++14

使用auto关键字进行编程时,有时可以方便地了解编译器在编译时使用的类型.如果编译中止我需要知道的类型并不重要.简单的例子:

std::vector< int > s{1, 2, 3}; 

for (auto elem : s) {
    elem = 5;
}   

for (auto elem : s) {
    std::cout << elem << std::endl;
}   
Run Code Online (Sandbox Code Playgroud)

将打印

1
2
3
Run Code Online (Sandbox Code Playgroud)

因为elem属于类型int,而不是int&.尝试编译代码并获得elem早期捕获此类错误的类型会很好.

Jar*_*d42 5

经典的方法是在没有定义的情况下声明模板结构:

template <typename> struct Debug;
Run Code Online (Sandbox Code Playgroud)

然后使用它:

template struct Debug<std::string>;
Run Code Online (Sandbox Code Playgroud)

要么

for (auto elem : s) {
    Debug<decltype(elem)>{};

    elem = 5;
}
Run Code Online (Sandbox Code Playgroud)

消息错误看起来像

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)>{};
Run Code Online (Sandbox Code Playgroud)

演示

顺便说一句,现在有些IDE显示鼠标结束时的类型auto或变量.