使用 operator[] 和 operator int() 的模糊重载

Ambiguous overloading with operator[] and operator int()

我正在创建一个 class 项,每个项都是 key/value 对。此外,每个项目还可能包含子项目:

#include <string>
#include <vector>
#include <iostream>


class Item
{
    private:
        std::string key;
        unsigned int value;
        std::vector<Item> subitems;


    public:
        Item( const std::string& key = "", const int& value = 0 )
        : key( key ), value( value ){ };


    public:
        // Search or Create new SubItem.
        Item& operator[]( const std::string& key )
        {
            for( auto& subitem : subitems )
                if( subitem.key == key )
                    return subitem;

            subitems.push_back( Item( key ));
            return subitems.back( );
        }


    public:
        // Assign new value to Item.
        Item& operator=( const int& value )
        {
            this->value = value;
            return *this;
        }


    public:
        // Get value from Item.
        operator unsigned int( ) const
        {
            return value;
        }
};



int main( void )
{
    Item item;


    item["sub"] = 42;
    unsigned int sub = item["sub"];


    std::cout << std::to_string( sub ) << std::endl;
    return 0;
}

当我尝试编译它时,我得到:

错误:“operator[]”的不明确重载(操作数类型为“Item”和“const char [4]”)

如果我创建一个成员方法 unsigned int Get() 而不是 operator int() 它会编译。但我希望 class 的工作方式与 std::map 的工作方式相同:

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



int main( void )
{
    std::map<std::string, unsigned int> item;


    item["sub"] = 42;
    unsigned int sub = item["sub"];


    std::cout << std::to_string( sub ) << std::endl;
    return 0;
}

我怎样才能让它工作? 谢谢!

问题是您与内置 operator[](unsigned int, const char *) 冲突(是的,这是一回事)。

在应用 operator[] 之前将操作数隐式转换为 std::string 或将 Item 隐式转换为 unsigned int 对编译器来说是等效的,因此它可以'不要在两者之间选择。

您可以通过向您的 class' operator[] 添加显式 const char* 重载来解决此问题,该重载遵循您的 std::string 实现。

// Search or Create new SubItem.
Item& operator[]( const char* key ) {
    return (*this)[std::string(key)];
}