c – 是否有可能在没有黑客的情况下“赞美”`std :: pair`的字段
发布时间:2020-12-16 06:54:44 所属栏目:百科 来源:网络整理
导读:在C中,编译以下代码: std::pair int,int x;static_cast std::pair const int,int* (x); 给出错误: error: invalid static_cast from type ‘std::pairint,int*’ to type ‘std::pairconst int,int*’ 我或多或少地理解为什么会发生这种情况,因为cv-限定模
在C中,编译以下代码:
std::pair <int,int> x; static_cast <std::pair <const int,int>*> (&x); 给出错误: error: invalid static_cast from type ‘std::pair<int,int>*’ to type ‘std::pair<const int,int>*’ 我或多或少地理解为什么会发生这种情况,因为cv-限定模板参数列表中的类型原则上可以给出“不兼容”的结果.即使在这种情况下它没有,编译器也无法知道它. 无论如何,是否有一种非hackish方式来执行此转换?我担心将reinterpret_cast用于任何事情,因为之前我遇到过类型惩罚问题.此外,我不能使用临时代码,因为这是性能关键代码. 编辑: 这就是我正在做的事情.我正在实现一个与std :: unordered_map兼容的自定义容器接口.因此,它的value_type必须是一对< const key_type,mapped_type>.对于某些优化,我需要在内部存储值为< key_type,mapped_type>,而不是const.但是,如果我这样做,我不能(没有reinterpret_cast)在容器上实现迭代器,因为它们需要返回对值的引用,并且我只引用了这些非const对. 解决方法
这不是演员,但你可以做到以下几点:
std::pair<int,int> x; std::pair<const int,int> y( x ); 这应该按照§20.2.2/ 4进行. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |