casting non const to const in c++

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?


Solution 1:

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:

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:

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:

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:

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