【发布时间】:2015-12-27 11:12:29
【问题描述】:
我正在阅读有关 const_cast 的内容,它似乎不安全且没有多大帮助。 SO 中关于它的best answer 声明它在这样的场景中很有用:
void func(const char* param, bool modify){
if(modify)
//const_cast and change param
// stuff that do not change param
}
虽然这是一种可能的用途,但它也有风险,因为您必须正确地提供“修改”的值,否则您将获得未定义的行为,因为您正在更改本应保持不变的内容。我想知道您是否可以在不必提供这个额外参数的情况下实现相同的功能,为此您很可能需要检查 const 限定符的存在。
我发现的 closes 是 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)
我也尝试过使用类似的函数签名,它们仅在“const”限定符上有所不同,但这被视为重新定义。那么有可能做到吗?如果可以,怎么做?
【问题讨论】: