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

前端 未结 15 1120
伪装坚强ぢ
伪装坚强ぢ 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:38

    With C++11 you can define a Property class template and use it like this:

    class Test{
    public:
      Property Number{this,&Test::setNumber,&Test::getNumber};
    
    private:
      int itsNumber;
    
      void setNumber(int theNumber)
        { itsNumber = theNumber; }
    
      int getNumber() const
        { return itsNumber; }
    };
    

    And here ist the Property class template.

    template
    class Property{
    public:
      using SetterType = void (C::*)(T);
      using GetterType = T (C::*)() const;
    
      Property(C* theObject, SetterType theSetter, GetterType theGetter)
       :itsObject(theObject),
        itsSetter(theSetter),
        itsGetter(theGetter)
        { }
    
      operator T() const
        { return (itsObject->*itsGetter)(); }
    
      C& operator = (T theValue) {
        (itsObject->*itsSetter)(theValue);
        return *itsObject;
      }
    
    private:
      C* const itsObject;
      SetterType const itsSetter;
      GetterType const itsGetter;
    };
    

提交回复
热议问题