casting non const to const in c++

C++TypesCastingConstants

C++ Problem Overview


I know that you can use const_cast to cast a const to a non-const.

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

C++ Solutions


Solution 1 - C++

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

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(); 
    }
};

Solution 2 - C++

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

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

Use:

CallFunc( as_const(variable) );

Instead of:

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

Solution 3 - C++

You don't need const_cast to add constness:

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

Please read through this question and answer for details.

Solution 4 - C++

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

Solution 5 - C++

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

Solution 6 - C++

const_cast can be used to add constness behavior too.

From cplusplus.com:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkamikaze_pilotView Question on Stackoverflow
Solution 1 - C++MottiView Answer on Stackoverflow
Solution 2 - C++Scott LanghamView Answer on Stackoverflow
Solution 3 - C++Ozair KafrayView Answer on Stackoverflow
Solution 4 - C++Jerry CoffinView Answer on Stackoverflow
Solution 5 - C++Guillaume ParisView Answer on Stackoverflow
Solution 6 - C++beduinView Answer on Stackoverflow