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

Creating a Variant class and std::map<Variant, Variant>

本文关键字:变体 gt map lt std 一个 创建      更新时间:2023-10-16

我插入了一个简单的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; }
~~~~^~~~~

这是我的变体类:

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
}

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

因此,如果你想在映射中使用Variant(我相信这只适用于键(,你需要为它提供一个operator<()。你可以在这里找到一些例子。

或者,您需要一个比较函数。这也可行。