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

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

In C++, the compiling the following code:

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

gi

相关标签:
2条回答
  • 2021-01-19 23:46

    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.

    0 讨论(0)
  • 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<const int,int>& rx = reinterpret_cast<std:::pair<const int,int>&>(x);
    

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

    0 讨论(0)
提交回复
热议问题