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;
}