mardi 4 février 2020

more than one operator "[]" matches these operands

I have a class that has both implicit conversion operator() to intrinsic types and the ability to access by a string index operator[] that is used for a settings store. It compiles and works very well in unit tests on gcc 6.3 & MSVC however the class causes some ambiguity warnings on intellisense and clang which is not acceptable for use.

Super slimmed down version: https://onlinegdb.com/rJ-q7svG8

#include <memory>
#include <unordered_map>
#include <string>


struct Setting
{
    int data; // this in reality is a Variant of intrinsic types + std::string
    std::unordered_map<std::string, std::shared_ptr<Setting>> children;
    template<typename T>
    operator T()
    {
        return data;
    }
    template<typename T>
    Setting & operator=(T val)
    {
        data = val;
        return *this;
    }
    Setting & operator[](const std::string key)
    {
        if(children.count(key))
            return *(children[key]);
        else
        {
            children[key] = std::shared_ptr<Setting>(new Setting());
            return *(children[key]);
        }
    }
};

Usage:

    Setting data;
    data["TestNode"] = 4;
    data["TestNode"]["SubValue"] = 55;
    int x = data["TestNode"];
    int y = data["TestNode"]["SubValue"];
    std::cout << x <<std::endl;
    std::cout << y;

output:
4
55

Error message is as follows:

more than one operator "[]" matches these operands:

built-in operator "integer[pointer-to-object]" function

"Setting::operator[](std::string key)"

operand types are: Setting [ const char [15] ]

I understand why the error/warning exists as it's from the ability to reverse the indexer on an array with the array itself (which by itself is extremely bizarre syntax but makes logical sense with pointer arithmetic).

char* a = "asdf";
char b = a[5];
char c = 5[a];
b == c

I am not sure how to avoid the error message it's presenting while keeping with what I want to accomplish. (implicit assignment & index by string)

Is that possible?

Note: I cannot use C++ features above 11.

Aucun commentaire:

Enregistrer un commentaire