检查变量是否是常量限定的

gui*_*nca 2 c++ constants c++11

我正在阅读关于const_cast的内容,它看起来不安全,而且不是很有帮助.在SO中关于它的最佳答案表明它在这样的场景中会有用:

void func(const char* param, bool modify){
    if(modify)
        //const_cast and change param
    // stuff that do not change param
}
Run Code Online (Sandbox Code Playgroud)

虽然这是一种可能的用法,但它有风险,因为你必须正确地提供"修改"的值,否则你会得到一个未定义的行为,因为你正在改变应该是常量的东西.我想知道你是否可以实现相同的功能,而不必提供额外的参数,为此你很可能需要检查const限定符的存在.

我发现关闭的东西是std函数is_const,但它似乎仅限于一种不同的用法:

is_const<const int>::value //returns true
is_const<int>::value // returns false
const int myVar=1;
is_const<myVar>::value // what it would look like ( does not compile)
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用类似的功能签名,只有"const"限定符不同,但这被认为是重新定义.所以可以做到这一点吗?如果是这样,怎么办呢?

Que*_*tin 8

您可以std::is_const<decltype(myVar)>::value用来检查是否myVar已声明为const.

但是,如果myVar是指针或对另一个对象的引用,则无法知道该对象是否const来自函数内部.

  • @guivenca,您需要为此使用`std::remove_pointer_t&lt;decltype(param)&gt;`:指针是非`const`,它的指针是`const`。 (2认同)