Is it possible to “constify” a field of `std::pair` without hacks?

核能气质少年 提交于 2019-12-01 18:39:48

That's not a cast, but you can do the following:

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

This should work according to §20.2.2/4.

How about this:

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_;
};

I know, it's different, those are functions. If you're really desperate, you can turn first and second into objects of some proxy type which delay-evaluate *f_ and *s_.
However, in the end there's always a way users can tell the difference.


I think the following would be reasonably safe and portable, although, of course, with reinterpret_cast nothing is guaranteed:

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

It feels dirty, though. I'm now going to wash my hands.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!