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

前端 未结 2 407
北海茫月
北海茫月 2021-01-19 22:55

In C++, the compiling the following code:

std::pair   x;
static_cast *> (&x);

gi

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-19 23:49

    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& rx = reinterpret_cast&>(x);
    

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

提交回复
热议问题