The following piece of code compiles fine
#include <iostream>
#include <map>
#include <memory>
using namespace std;
class child {
public:
child(std::string name,uint32_t age) : name(name),age(age){
}
std::string name;
uint32_t age;
};
class parent {
public:
uint32_t age;
parent(std::string name){
age = 10;
}
std::map<uint32_t, std::shared_ptr<child>> child_by_age;
std::map<std::string, std::shared_ptr<child>> child_by_name;
child& operator[](const uint32_t& num){
return *(child_by_age[num]);
}
child& operator[](const std::string& n){
return *(child_by_name[n]);
}
void addChild(const child& ch){
auto ch_obj = std::make_shared<child>(ch);
child_by_age.emplace(ch.age, ch_obj);
child_by_name.emplace(ch.name, ch_obj);
}
};
class top {
public:
parent p1;
top():p1("p1"){
p1.addChild(child("c0",0));
p1.addChild(child("c1",1));
}
void run(){
p1["c0"].name = "name";
p1[0].name = "name1";
}
};
int main(){
top t;
t.run();
return 0;
}
But the moment I add following conversion operator
operator uint32_t() const{
return age;
}
I am getting the following error
operator_overload.cpp: In member function ‘void top::run()’: operator_overload.cpp:50:11: error: ambiguous overload for ‘operator[]’ (operand types are ‘parent’ and ‘const char [3]’) p1["c0"].name = "name"; ^ operator_overload.cpp:50:11: note: candidate: operator[](long int, const char*) operator_overload.cpp:28:12: note: candidate: child& parent::operator[](const string&) child& operator[](const std::string& n){ ^~~~~~~~
I am not sure to understand why the compiler complains on subscript operator when I add conversion operator
return *(child_by_age[num]);-- Probably not related to your issue, but you do realize thatchild_by_agewill add an entry automatically if keynumdoes not exist? Usage ofstd::map::operator[]as a look-up mechanism is known for bugs appearing, most notably having the map "mysteriously" increase in size if the key doesn't exist.ageto be exactly 32 bits wide. Plain oldunsignedwould work just fine, unless you're dealing with people who have extremely long lifetimes. Andunsignedhas the (minor) advantage of always existing, even on peculiar architectures.