检查变量是否为常量限定 [英] Checking if a variable is constant qualified

查看:94
本文介绍了检查变量是否为常量限定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关const_cast的信息,它似乎不安全,也没有很大帮助。关于SO的最佳答案指出,在以下情况下它将很有用:

I was reading about const_cast and it seemed unsafe and not very helpful. The best answer about it in SO states the it would be useful in a scenario like this:

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

尽管这是一种可能的用法,这样做有风险,因为您必须正确提供 modify的值,否则您将获得不确定的行为,因为您正在更改原本应该不变的东西。我想知道是否可以在不必提供此额外参数的情况下实现相同的功能,并且为此,您很可能需要检查const限定符的存在。

Although this a possible use, it has its risks because you have to correctly provide the value of "modify", or else you will get an undefined behaviour since you are changing something that was supposed to be constant. I wonder if you could achieve the same functionality without having to supply this extra argument and for that you would most likely need to check the existence of a const qualifier.

我发现的是std函数 is_const ,但似乎仅限于另一种用法:

The closes thing I found was the std function is_const, but it seems to be limited to a different kind of usage:

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)

我也尝试过使用类似的函数签名,只是 const限定符不同,但这被认为是重新定义。那么有可能做到吗?如果是这样,怎么办呢?

I've also tried using similar function signatures that only differ by a "const" qualifier, but that is perceived as a redefinition. So is it possible at all to do it? If so, how can it be done?

推荐答案

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

You can use std::is_const<decltype(myVar)>::value to check whether myVar has been declared as const.

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

However, if myVar is a pointer or a reference to another object, there is no way of knowing if that object is const or not from inside the function.

这篇关于检查变量是否为常量限定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆