Does C++11 have C#-style properties?

前端 未结 15 1091
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 03:16

In C#, there is a nice syntax sugar for fields with getter and setter. Moreover, I like the auto-implemented properties which allow me to write

public Foo fo         


        
15条回答
  •  暖寄归人
    2020-11-28 03:48

    C++ doesn't have this built in, you can define a template to mimic properties functionality:

    template 
    class Property {
    public:
        virtual ~Property() {}  //C++11: use override and =default;
        virtual T& operator= (const T& f) { return value = f; }
        virtual const T& operator() () const { return value; }
        virtual explicit operator const T& () const { return value; }
        virtual T* operator->() { return &value; }
    protected:
        T value;
    };
    

    To define a property:

    Property x;
    

    To implement a custom getter/setter just inherit:

    class : public Property {
        virtual float & operator = (const float &f) { /*custom code*/ return value = f; }
        virtual operator float const & () const { /*custom code*/ return value; }
    } y;
    

    To define a read-only property:

    template 
    class ReadOnlyProperty {
    public:
        virtual ~ReadOnlyProperty() {}
        virtual operator T const & () const { return value; }
    protected:
        T value;
    };
    

    And to use it in class Owner:

    class Owner {
    public:
        class : public ReadOnlyProperty { friend class Owner; } x;
        Owner() { x.value = 8; }
    };
    

    You could define some of the above in macros to make it more concise.

提交回复
热议问题