ENH: HashTable cfind() method returning a const_iterator

- This follows the same idea as cbegin/cend and is helpful when using
  C++11 auto to ensure we have unambiguous const-safe access.

  Previously:
  ====
    typename someLongClass::const_iterator iter = someTable.find(key);

    ... later on:
    *iter = value; // Oops, but caught by compiler.

  We can save some typing with auto, but it is uncertain what we get:
  ====
    auto iter = someTable.find(key);
        // iterator or const_iterator?
        // depends on someTable having const or non-const access.

    ... later on:
    *iter = value;  // Oops, but not caught by compiler.

  Using cfind instead, auto will deduce const_iterator as the type:
  ====
    auto iter = someTable.cfind(key);  // definitely const_iterator

    ... later on:
    *iter = value; // Oops, but caught by compiler.
This commit is contained in:
Mark Olesen
2017-05-26 12:42:30 +02:00
parent 2af602c2f4
commit b83007594a
5 changed files with 34 additions and 4 deletions

View File

@ -74,7 +74,7 @@ Foam::HashTable<T, Key, Hash>::HashTable(const label size)
{
table_ = new hashedEntry*[tableSize_];
for (label hashIdx = 0; hashIdx < tableSize_; hashIdx++)
for (label hashIdx = 0; hashIdx < tableSize_; ++hashIdx)
{
table_[hashIdx] = nullptr;
}
@ -203,6 +203,17 @@ Foam::HashTable<T, Key, Hash>::find
(
const Key& key
) const
{
return this->cfind(key);
}
template<class T, class Key, class Hash>
typename Foam::HashTable<T, Key, Hash>::const_iterator
Foam::HashTable<T, Key, Hash>::cfind
(
const Key& key
) const
{
if (nElmts_)
{
@ -912,7 +923,7 @@ bool Foam::HashTable<T, Key, Hash>::operator==
for (const_iterator iter = rhs.cbegin(); iter != rhs.cend(); ++iter)
{
const_iterator other = find(iter.key());
const_iterator other = this->cfind(iter.key());
if (!other.found() || other.object() != iter.object())
{