Multimap插入键typeinfo与std :: make

编程入门 行业动态 更新时间:2024-10-26 18:16:00
Multimap插入键typeinfo与std :: make_pair vs std :: pair构造函数(Multimap insert key typeinfo with std::make_pair vs std::pair constructor)

我想了解为什么以下代码使用std :: pair构造函数是有效的:

码:

std::multimap< std::type_index, void * > mm; mm.insert(std::pair<std::type_index, void *>(typeid(int), 0));

并在使用std :: make_pair时出现编译错误:

错误:

C2248 'type_info::type_info' cannot access private member declared in class 'type_info'

代码:

std::multimap< std::type_index, void * > mm; mm.insert(std::make_pair(typeid(int), 0));

有什么线索吗? 谢谢 !

I would like to understand why the following code is valid using std::pair constructor :

Code:

std::multimap< std::type_index, void * > mm; mm.insert(std::pair<std::type_index, void *>(typeid(int), 0));

And gives compiling error when using std::make_pair:

Error:

C2248 'type_info::type_info' cannot access private member declared in class 'type_info'

Code :

std::multimap< std::type_index, void * > mm; mm.insert(std::make_pair(typeid(int), 0));

Any clues ? Thank you !

最满意答案

typeid的返回类型是std::type_info对象,它没有定义构造函数。 当make_pair从传入的参数中推导出其输出对的模板参数时,它会推导出std::pair<std::type_info, int> 。 然后,由于上述原因,它无法创建所需的对。

您的另一行使用显式模板参数创建对: std::pair<std::type_index, void *> 。 这一次,你正在创建一个std::type_index对象,它有一个构造函数,它接受一个std::type_info - 正是你给它的东西。 所以没问题。

如果还给出了显式模板参数,那么make_pair行将编译:

mm.insert(std::make_pair<std::type_index, void *>(typeid(int), 0));

The return type of the typeid is a std::type_info object, which has no constructors defined. As make_pair deduces the template arguments for its output pair from the parameters passed in, it deduces std::pair<std::type_info, int>. It then fails to create the required pair for the above reason.

Your other line creates the pair with explicit template parameters: std::pair<std::type_index, void *>. This time, you are creating an std::type_index object, which does have a constructor, which takes an std::type_info - exactly what you're giving it. So no problems.

Your make_pair line would compile if it was also given explicit template parameters:

mm.insert(std::make_pair<std::type_index, void *>(typeid(int), 0));

更多推荐

本文发布于:2023-08-05 21:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1437753.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Multimap   typeinfo   std

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!