在 C++ 中将非 const 转换为 const

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5853833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:02:27  来源:igfitidea点击:

casting non const to const in c++

c++typescastingconstantsconst

提问by kamikaze_pilot

I know that you can use const_castto cast a constto a non-const.

我知道您可以使用const_cast将 aconst转换为非const.

But what should you use if you want to cast non-constto const?

但是,如果您想将 non- constto 转换为 ,您应该使用什么const

采纳答案by Motti

const_castcan be used in order remove oradd constness to an object. This can be useful when you want to call a specific overload.

const_cast可用于为对象删除添加常量。当您想要调用特定的重载时,这会很有用。

Contrived example:

人为的例子:

class foo {
    int i;
public:
    foo(int i) : i(i) { }

    int bar() const {
        return i;    
    }

    int bar() { // not const
        i++;
        return const_cast<const foo*>(this)->bar(); 
    }
};

回答by Scott Langham

STL since C++17 now provides std::as_constfor exactly this case.

从 C++17 开始的 STL 现在std::as_const正好提供这种情况。

See: http://en.cppreference.com/w/cpp/utility/as_const

请参阅:http: //en.cppreference.com/w/cpp/utility/as_const

Use:

用:

CallFunc( as_const(variable) );

Instead of:

代替:

CallFunc( const_cast<const decltype(variable)>(variable) );

回答by Ozair Kafray

You don't need const_castto add constness:

您不需要const_cast添加constness:

class C;
C c;
C const& const_c = c;

Please read through this question and answerfor details.

请通读此问题和答案以了解详细信息。

回答by Jerry Coffin

You can use a const_castif you want to, but it's not really needed -- non-const can be converted to const implicitly.

const_cast如果您愿意,您可以使用 a ,但它并不是真正需要的——非常量可以隐式转换为 const。

回答by Guillaume07

You have an implicit conversion if you pass an non const argument to a function which has a const parameter

如果将非 const 参数传递给具有 const 参数的函数,则会进行隐式转换

回答by beduin

const_castcan be used to add constness behavior too.

const_cast也可用于添加constness 行为。

From cplusplus.com:

来自cplusplus.com

This type of casting manipulates the constness of an object, either to be set or to be removed.

这种类型的转换操纵对象的常量性,要么设置要么删除。