0

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

2
  • 2
    return *(child_by_age[num]); -- Probably not related to your issue, but you do realize that child_by_age will add an entry automatically if key num does not exist? Usage of std::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. Commented Jan 9 at 19:53
  • Side note: there doesn't seem to be a need to force age to be exactly 32 bits wide. Plain old unsigned would work just fine, unless you're dealing with people who have extremely long lifetimes. And unsigned has the (minor) advantage of always existing, even on peculiar architectures. Commented Jan 9 at 20:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.