创建一个Variant类和std :: map <Variant,Variant>

Guerlando OC

我创建了一个简单的Variant类来存储字符串,整数,双精度型等。我试图使用类型映射,std::map<Variant, Variant>但是却遇到了这个奇怪的错误:

In file included from /usr/include/c++/7/string:48:0,
                 from /home/dev/proj/cpp/common/Variant.h:3,
                 from /home/dev/proj/cpp/common/Event.h:3,
                 from /home/dev/proj/cpp/common/Event.cpp:1:
/usr/include/c++/7/bits/stl_function.h: In instantiation of 'constexpr bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Variant]':
/usr/include/c++/7/bits/stl_map.h:511:32:   required from 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = Variant; _Tp = Variant; _Compare = std::less<Variant>; _Alloc = std::allocator<std::pair<const Variant, Variant> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = Variant; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = Variant]'
/home/dev/orwell/cpp/common/Event.cpp:33:18:   required from here
/usr/include/c++/7/bits/stl_function.h:386:20: error: no match for 'operator<' (operand types are 'const Variant' and 'const Variant')
       { return __x < __y; }
                ~~~~^~~~~

这是我的Variant类别:

class Variant
{
public:
    enum class Type
    {
        Integer,
        Double,
        String
    };

    Variant()
    {
    }

    Variant(int integer)
    {
        this->type = Type::Integer;
        setInteger(integer);
    }

    Variant(std::string string)
    {
        this->type = Type::String;
        setString(string);
    }

    Variant(double _double)
    {
        this->type = Type::Double;
        setDouble(_double);
    }

    Type type;

这是发生错误的地方:

void Event::add(std::string key, std::string value) {
    this->map[key] = Variant(value); //problem here
}
Chipster

std::map是一个排序的数组。为此,它使用<运算符。

因此,如果要Variant在地图中使用(我相信这仅适用于键),则需要为其提供operator<()您可以在此处找到一些示例

或者,您将需要一个比较功能那也可以。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章