问题描述
在C ++中,编译以下代码:
In C++, the compiling the following code:
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-qualifying模板参数列表中的类型原则上可以给出不兼容结果。即使在这种情况下,编译器也无法知道它。
I more or less understand why it happens, as cv-qualifying a type in a template parameter list can, in principle, give an "incompatible" result. And even if in this case it doesn't, compiler has no way to know it.
无论如何,有一个非黑客的方式来执行这个转换?我警惕使用 reinterpret_cast
的任何东西,因为我以前的类型冲突问题。此外,我不能使用临时值,因为这是性能关键代码。
Anyway, is there a non-hackish way to perform this conversion? I'm wary of using reinterpret_cast
for anything as I've been by type-punning problems before. Also, I can't use temporaries since this is in performance-critical code.
EDIT:
这里是我在做什么。我实现一个自定义容器接口兼容 std :: unordered_map
。因此,它的 value_type
需要是对< const key_type,mapped_type>
。对于一些优化,我需要内部存储值 pair< key_type,mapped_type>
,而不是 const
。但是,如果我这样做,我不能(不
reinterpret_cast
)在容器上实现迭代器,因为他们需要返回对值的引用,我只引用这些非-const pair。
Here is what I'm doing. I'm implementing a custom container interface-compatible with std::unordered_map
. Because of that, its value_type
needs to be a pair <const key_type, mapped_type>
. For some optimization, I need to internally store the values as pair <key_type, mapped_type>
, without const
. However, if I do that, I can't (without reinterpret_cast
) implement iterators over the container, as they need to return references to values and I have only references to these non-const pairs.
推荐答案
这不是强制类型,但可以执行以下操作:
That's not a cast, but you can do the following:
std::pair<int, int> x;
std::pair<const int, int> y( x );
这应该根据&20.2.2 / 4。工作
This should work according to §20.2.2/4.
这篇关于是否可能“固定” `std :: pair`的字段没有hack?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!