Jak rozszerzyć klasę std::map?

0

Chciałbym rozszerzyć klasę std::map<string,string> o możliwość rzutowania na bool, żeby można było łatwo sprawdzić czy obiekt jest pusty czy ma jakieś elementy. Zrobiłem coś takiego:

class DBRow: public std::map<string,string> {
public:
	operator bool();
};

DBRow::operator bool() {
  return !this->empty();
}

I teraz chcę zrobić:

	DBRow r;
	r["name"] = "a";
	if(r) {
		cout << "ok";
	}

No i mi wyświetla komunikat na drugiej linii

error: ambiguous overload for ‘operator[]’ in ‘r["name"]’
note: candidates are: operator[](int, const char*) <built-in>

Dlaczego tak się dzieje? Dodam, że ze zwykłym std::map przypisywanie działa:

std::map<string,string> s;
s["name"] = "a";

Jak poprawnie dodać do std::map konwersję na bool?

0
DBRow r; string klucz="name";
r[klucz] = "a";

jest tak, poniewaz:

 "mama"[0] === 0["mama"]

tak sa zdefiniowane operatory [] dla wskaznikow oraz licz calkowitych
"napis" to char*, nie string!
Twoja klasa definiuje operator rzutowania na bool, czyli na liczbe calkowita..
std::string definiuje konwersje string<-char*..

stad, piszac r["cos"] kompilator nie wie, czy chodzi Ci o
(r.operator bool())["cos"] === "cos"[r.operator bool()] === "cos"[0] ---- w tej opcji sa dwie 'implicit' konwersje
czy tez o:
r. map::operator[] ("cos", args...

jesli nie chcesz, aby kompilator wychwytywal domylsny operator[] dla char*, np. utworz wlasny operator char* dla Twojej klasy ktory przykryje tamten:

#include <iostream>
#include <string>
#include <map>

class DBRow: public std::map<std::string,std::string> {
public:
    operator bool() {return !this->empty();}

    std::string & operator[] (const char* const ptr) {
        return std::map<std::string,std::string>::operator[](ptr);
    }

    std::string & operator[] (std::string const & ptr) {
        return std::map<std::string,std::string>::operator[](ptr);
    }
};

int main()
{
    DBRow test;
    std::string klucz = "ble";
    test[klucz] = "bum";
    test["ble"] = "bum";
    std::cout << (test ? "jest" : "nie ma") << std::endl;
}
0

Bardzo dziękuję za pomoc i wyjaśnienie.

1 użytkowników online, w tym zalogowanych: 0, gości: 1