【问题标题】:Is it possible to "constify" a field of `std::pair` without hacks?是否可以在没有 hack 的情况下“构造”`std::pair` 的字段?
【发布时间】:2010-09-03 18:27:18
【问题描述】:

在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 限定模板参数列表中的类型原则上会给出“不兼容”的结果。即使在这种情况下它没有,编译器也无法知道它。

无论如何,有没有一种非黑客的方式来执行这种转换?我对使用reinterpret_cast 持谨慎态度,因为我以前遇到过类型双关语问题。另外,我不能使用临时代码,因为这是对性能至关重要的代码。

编辑:

这就是我正在做的事情。我正在实现与std::unordered_map 兼容的自定义容器接口。因此,它的value_type 必须是pair &lt;const key_type, mapped_type&gt;。对于一些优化,我需要在内部将值存储为pair &lt;key_type, mapped_type&gt;,而不是const。但是,如果我这样做,我不能(没有reinterpret_cast)在容器上实现迭代器,因为它们需要返回对值的引用,而我只有对这些非常量对的引用。

【问题讨论】:

  • 您的预期用例是什么?我很难理解如何使用它。
  • 你可以保留两个这样的结构并定义一个从 less const 到 more const 的转换函数。
  • @James McNellis:我的猜测是他有一个返回 pair 的函数和另一个返回 pair* 的函数
  • @James McNellis:地图有pair &lt;const key_type, mapped_type&gt; 作为他们的value_type,所以我需要(或似乎需要,也许还有其他选择)进行一些优化。
  • @doublep:也许如果你展示你试图优化的代码会有所帮助。

标签: c++ casting constants std-pair


【解决方案1】:

这不是演员表,但您可以执行以下操作:

std::pair<int, int>  x;
std::pair<const int, int> y( x );

这应该根据 §20.2.2/4 起作用。

【讨论】:

  • 诀窍是y.second 需要引用与x.second 相同的变量。也许std::pair&lt;const int, int&amp;&gt; y(x.first, x.second) 可能有用。
【解决方案2】:

这个怎么样:

template< typename T1, typename T2 >
struct ref_pair {
public:
    typedef const T1 first_type;
    typedef T2 second_type;

    ref_pair(first_type& f, second_type& s) : f_(f), s_(s) {}

    first_type& first() {return *f_;}
    second_type& second() {return *s_;}
private:
    first_type* f_;
    second_type* s_;
};

我知道,它是不同的,那些是功能。如果你真的很绝望,你可以把 firstsecond 变成一些代理类型的对象,延迟评估 *f_*s_
然而,最终总有一种方法可以让用户分辨出来。


我认为以下内容是相当安全和便携的,当然,reinterpret_cast 没有任何保证:

std:::pair<const int,int>& rx = reinterpret_cast<std:::pair<const int,int>&>(x);

不过感觉很脏。我现在要洗手了。

猜你喜欢
  • 1970-01-01
  • 2011-06-06
  • 2020-09-09
  • 2021-12-29
  • 2016-07-27
  • 2010-12-25
  • 2021-07-29
  • 2014-06-16
  • 2018-01-03
相关资源
最近更新 更多