How to Define or Implement C# Property in ISO C++?

后端 未结 3 767
一整个雨季
一整个雨季 2021-01-27 18:09

How to Define or Implement C# Property in ISO C++ ?

Assume following C# code :

int _id;

int ID
{
    get { return _id; }
    set { _id = value; }
}
         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-27 18:43

    Quite simply. I'd argue this even has no overhead compared to making the variable public. However, you can't modify this any further. Unless, of course, you add two more template parameters that are call backs to functions to call when getting and setting.

    template
    class CProperty
    {
    public:
        typedef TNDataType TDDataType;
    private:
        TDDataType m_Value;
    public:
        inline TDDataType& operator=(const TDDataType& Value)
        {
            m_Value = Value;
            return *this;
        }
    
        inline operator TDDataType&()
        {
            return m_Value;
        }
    };
    

    EDIT: Don't make the call back functions template parameters, just data members that are constant and must be initialized in the constructor for the property. This inherently has greater overhead than simply writing a get and set method your self, because you're making function calls inside of your gets and sets this way. The callbacks will be set at run-time, not compile-time.

提交回复
热议问题