创建一个变体类和 std::map<变体,变体>
Creating a Variant class and std::map<Variant, Variant>
我插入了一个简单的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<()
。你可以在这里找到一些例子。
或者,您需要一个比较函数。这也可行。
相关文章:
- std::具有相同基类的类的变体
- 访问者访问变体并返回不同类型时出错
- 我应该使用什么来代替void作为变体中的替代类型之一
- 将shared_ptr移动到<StructA>shared_ptr<变体<结构A、结构 B>>
- 如何比较自定义类的std::变体
- 通过网络、跨平台传递std::变体是否安全
- 对于循环变体比较
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 标准::变体的赋值运算符
- 如何@ref同一方法的不同变体?
- 无限嵌套具有变体的地图
- Android Studio:如何在build.gradle中定义自定义宏(针对不同的构建变体),并让原生C / C++
- std::带有前向声明的变体
- 如何将 std::filesystem::p ath 转换为 LPCSTR,以便在 LoadLibrary() 变体之一
- 如何使用可变参数模板强制转换每个变体类型
- 标准::C++中的变体
- 你如何使std::变体的使用更"palatable",语法方面?
- 访问具有单状态的变体
- 确保无变体的型号安全
- 类型双关主题的变体:就地琐碎构造