Angular const: std :: map :: find () const overload

Consider the following snippet:

#include <map>

class C {
public:
    C() {}

    const int& f(const int& x) const
    {
        // Error: cannot cast const int* to int* const
        return myMap.find(&x)->second;

        // With a const_cast works:
        //return myMap.find(const_cast<int* const>(&x))->second;
    }

    std::map<int*, int> myMap;
};

int _tmain(int argc, _TCHAR* argv[])
{
    int x = 0;

    C c;
    c.f(x);

    return 0;
}

The error in is f()caused by overloading the map constant find()with const KeyType&. Since the key type of card is equal int*, this turns into int* const. f()accepts a parameter const int&, which is correct because the parameter never changes.

Unfortunately, this ends up doing a const int*in int* const, which loses the const specifier to int and does not compile.

This is annoying because the parameter is definitely not modified - it is just used for find (), but I still need const_castit.

Is there any way to write f()without const_cast?

+5
2

: const? (, , .) - *myMap.find(&x)->first = xxx; , , , .

+5

map std::map<const int*, int>; , , . , const int*, map. , .

+7

All Articles