如何在C++中使用BOOST_AUTO模拟'const auto'?

the*_*0ID 6 c++ boost c++11

使用BOOST_AUTO宏我们可以模拟auto在C++ 11之前不可用的关键字:

BOOST_AUTO( var, 1 + 2 ); // int var = 3
auto var = 1 + 2; // the same in C++11
Run Code Online (Sandbox Code Playgroud)

有什么方法可以效仿const auto吗?

const auto var = 1 + 2; // const int var = 3
Run Code Online (Sandbox Code Playgroud)

seh*_*ehe 5

你可以只包括"尾随"const:

#include <boost/typeof/typeof.hpp>

int main()
{
    BOOST_AUTO(const x, 42);

    static_assert(std::is_const<decltype(x)>(), "weehoo");
}
Run Code Online (Sandbox Code Playgroud)

由于const许多原因,尾随位置是限定符的唯一一致位置.这是其中之一:)