How to ignore a constant in a function template?

I have the following template function:

template<typename K, typename V>
bool hasKey( const std::map<K, V>& m, K& k ) {
    return m.find(k) != m.end();
}

The keys on the card are not const.

Now I can have it const K. How can I write a template that would allow me to pass as K andconst K` to a function?

Is the solution used const_castevery time I call a function?

+4
source share
2 answers

You can achieve what you want with the following

template <typename Key, typename Value, typename K>
bool hasKey(const std::map<Key, Value>& mp, const K& k) {
    return mp.find(k) != mp.end();
}

Thus, you are sure, looking at the declaration of the function, that not a single operand will be changed, since they are references to const.

non-const const ( rvalues) .find() std::map. , .find() const, , , , .

, , - ( ++ 14, . http://en.cppreference.com/w/cpp/container/map/find), , ?.

+7

hasKey Map:

template<typename Map>
bool hasKey(const Map& m, const typename Map::key_type& k) {
    return m.find(k) != m.end();
} 
+3

Source: https://habr.com/ru/post/1680608/


All Articles