Deduced type of “auto it = unordered_map.find(key)”?

独自空忆成欢 提交于 2019-12-04 05:48:34

I'm not aware of any place that takes a const_iterator where you couldn't simply pass an iterator instead, so this deficiency may not interfere much with day-to-day code writing. However, I do prefer to use const_iterators (and const in general) wherever I don't need mutating, in the interests of general communication, so I think adding a cfind() might be a useful addition to the future standard library.

I think this code could function as a simple workaround for what you're trying to achieve, though:

template<typename T>
auto use_as_const( T const &t ) -> T const & {
    return t;
}

This is a simple casting wrapper function, similar in style to move() and forward<T>(), to provide (and document) a constraint on individual usages of the object. You could then use it like this:

auto it1 = use_as_const( umii ).find(0);

This could also be used instead of leaning on cbegin() and cend(). Or, it could be used in range-based for loops:

for ( auto &element : use_as_const( some_vector_of_string ) ) {
    cout << element;
    // element = ""; // This line shouldn't compile.
}

In the above loop example, although I would generally prefer auto const &element : ..., I believe it would be unnecessary and element would still be deduced to be a const reference.

ecatmur

It's a bit of a deficiency; we have cbegin and cend but no corresponding cfind, etc.

I'd suggest using a utility function to get a const reference to the object, as per the answer to forcing use of cbegin()/cend() in range-based for:

template<typename T> constexpr const T &as_const(T &t) { return t; }

auto it1 = as_const(umii).find(0);
it1->second = 42; // fails
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!