0

I'm using quite often simple map lookup, where I want to avoid exception handling... Therefore I wrote first a "helper" function, then a simple derived class. However, I can NOT explain the compile error when using "find()" (and "end()") directly (1); it works when using "this->" (2) or "map<K, T>::" (3). Can anyone explain?

I hope the code/intention is clear enough.

Thanks, Gabriel

#include <iostream>
#include <map>

using namespace std;


//convenient helper
template <typename K, typename T> class map_ex: public map<K, T>
{
public:
  bool try_get(const K k, T &v)
  {
    auto f = find(k); //1: not found ??!
    //auto f = this->find(k); //2: works
    //auto f = map<K, T>::find(k); //3: works
    bool found = f != this->end();
    if(found) v = f->second;
    return found;
  };
};

int main()
{
    map_ex<string, string> m;
    m["test"] = "1";
    string v;
    m.try_get("test", v);
    std::cout << v << std::endl;
    return 0;
}
Gabriel C.
  • 31
  • 1
  • Dependent name -> `this->find(k)`. – Jarod42 Feb 14 '22 at 10:11
  • 1
    btw you do not need inheritance. The same functionalitly can be supplied via a free function (while inheriting from `std::map` is dangerous, you arent doing it in your code, but it can be easily used wrong) – 463035818_is_not_an_ai Feb 14 '22 at 10:20
  • ok, now I understand. @463035818_is_not_a_number I have used first a free function, but I just wanted to have an "OO look" :) – Gabriel C. Feb 14 '22 at 11:16
  • what is an "OO look" ? Placing everything inside a class is a "terrible look", its not what object orientation is about – 463035818_is_not_an_ai Feb 14 '22 at 11:19
  • In my (subjective) opinion, `m.try_get("test", v)` looks nicer than `try_get(m, "test", v)` – Gabriel C. Feb 14 '22 at 13:19
  • your (subjective) opinion is against a common recommendation to use free functions when possible. See https://stackoverflow.com/questions/21028773/free-function-versus-member-function and https://stackoverflow.com/questions/5989734/effective-c-item-23-prefer-non-member-non-friend-functions-to-member-functions and https://stackoverflow.com/questions/967538/c-member-functions-vs-free-functions?rq=1 – 463035818_is_not_an_ai Feb 15 '22 at 08:13

0 Answers0