How to copy (or swap) objects of a type that contains members that are references or const?

前端 未结 5 2070
生来不讨喜
生来不讨喜 2020-12-15 10:08

The problem I am trying to address arises with making containers such as an std::vector of objects that contain reference and const data members:



        
5条回答
  •  悲&欢浪女
    2020-12-15 10:39

    You can compose your class of members that take care of those restrictions but are assignable themselves.

    #include 
    
    template 
    class readonly_wrapper
    {
        T value;
    public:
        explicit readonly_wrapper(const T& t): value(t) {}
        const T& get() const { return value; }
        operator const T& () const { return value; }
    };
    
    struct Foo{};
    
    struct Bar {
      Bar (Foo & foo, int num) : foo_reference(foo), number(num) {}
    private:
      std::reference_wrapper foo_reference;  //C++11, Boost has one too
      readonly_wrapper number;
      // Mutable member data elided
    };
    
    #include 
    int main()
    {
      std::vector bar_vector;
      Foo foo;
      bar_vector.push_back(Bar(foo, 10));
    };
    

提交回复
热议问题