std::map 由于 "cannot convert argument 1 from 'std::pair<MyKey, MyValue>' to 'std::pair<const _Kty,_Ty> &&'" 无法编译插入
std::map insert doesn't compile due to "cannot convert argument 1 from 'std::pair<MyKey, MyValue>' to 'std::pair<const _Kty,_Ty> &&'"
我正在尝试为 <MyKey, MyValue>
创建一个 std::map。 MyKey
是枚举,MyValue
是外部 class。
调用myMap.insert({ key, value })
总是编译失败并出现错误
"cannot convert argument 1 from 'std::pair<MyKey, MyValue>' to 'std::pair<const _Kty,_Ty> &&'"
虽然基本数据类型总是与 std::map.insert()
一起工作,但当试图包含由其他人编写的 classes 时,这个问题经常发生。对于不同的第三方 classes,我尝试了很多解决方法,例如预先构造对象或在插入后设置它们的属性。但我还没有找到一种系统的方法来解决这个问题。似乎 std::map
比 python 的 dict
.
更难正确
示例:使用第三方库 cppzmq
、Visual Studio 2017
enum MyKey {
key1,
key2
}
std::map<MyKey, zmq::socket_t> mymap;
std::shared_ptr<zmq::context_t> g_context = std::make_shared<zmq::context_t>(1);
zmq:socket_t sock(*g_context, zmq::socket_type::pair);
mymap.insert({ key1, sock });
给我上面的错误。
这个错误是什么意思,通常如何解决?
请帮忙。
如果您想将一个只能移动的对象插入到 std::map
中,那么您唯一的选择就是将其移动到地图中。调整你的例子,你可以试试这个:
mymap.insert({key1, zmq:socket_t{*g_context, zmq::socket_type::pair}});
您也可以这样做:
zmq:socket_t sock{*g_context, zmq::socket_type::pair};
mymap.insert({key1, std::move(sock)});
// note that sock is in a "moved from" state after this point
我看到您来自 Python,可能不熟悉移动语义,因此 this question 的答案可能会有所帮助。
我正在尝试为 <MyKey, MyValue>
创建一个 std::map。 MyKey
是枚举,MyValue
是外部 class。
调用myMap.insert({ key, value })
总是编译失败并出现错误
"cannot convert argument 1 from 'std::pair<MyKey, MyValue>' to 'std::pair<const _Kty,_Ty> &&'"
虽然基本数据类型总是与 std::map.insert()
一起工作,但当试图包含由其他人编写的 classes 时,这个问题经常发生。对于不同的第三方 classes,我尝试了很多解决方法,例如预先构造对象或在插入后设置它们的属性。但我还没有找到一种系统的方法来解决这个问题。似乎 std::map
比 python 的 dict
.
示例:使用第三方库 cppzmq
、Visual Studio 2017
enum MyKey {
key1,
key2
}
std::map<MyKey, zmq::socket_t> mymap;
std::shared_ptr<zmq::context_t> g_context = std::make_shared<zmq::context_t>(1);
zmq:socket_t sock(*g_context, zmq::socket_type::pair);
mymap.insert({ key1, sock });
给我上面的错误。
这个错误是什么意思,通常如何解决?
请帮忙。
如果您想将一个只能移动的对象插入到 std::map
中,那么您唯一的选择就是将其移动到地图中。调整你的例子,你可以试试这个:
mymap.insert({key1, zmq:socket_t{*g_context, zmq::socket_type::pair}});
您也可以这样做:
zmq:socket_t sock{*g_context, zmq::socket_type::pair};
mymap.insert({key1, std::move(sock)});
// note that sock is in a "moved from" state after this point
我看到您来自 Python,可能不熟悉移动语义,因此 this question 的答案可能会有所帮助。