是否有可能在没有黑客的情况下“赞美”`std :: pair`的领域?

时间:2010-09-03 18:27:19

标签: c++ casting const std-pair

在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必须为pair <const key_type, mapped_type>。对于某些优化,我需要内部将值存储为pair <key_type, mapped_type>,而不是const。但是,如果我这样做,我不能(没有reinterpret_cast)在容器上实现迭代器,因为它们需要返回对值的引用,并且我只引用了这些非const对。

2 个答案:

答案 0 :(得分:1)

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

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

这应该符合§20.2.2/ 4。

答案 1 :(得分:0)

这个怎么样:

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);
但是,感觉很脏。我现在要洗手了。