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

后端 未结 3 766
一整个雨季
一整个雨季 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:46

    As Alexandre C. has already stated, it's very awkward and not really worth it, but to give an example of how you might do it.

    template 
    class Property
    {
        private:
            void (TClass::*m_fp_set)(TProperty value);
            TProperty (TClass::*m_fp_get)();
            TClass * m_class;
    
            inline TProperty Get(void)
            {
                return (m_class->*m_fp_get)();
            }
    
            inline void Set(TProperty value)
            {
                (m_class->*m_fp_set)(value);
            }
    
        public:
            Property()
            {
                m_class = NULL;
                m_fp_set = NULL;
                m_fp_set = NULL;
            }
    
            void Init(TClass* p_class, TProperty (TClass::*p_fp_get)(void), void (TClass::*p_fp_set)(TProperty))
            {
                m_class = p_class;
                m_fp_set = p_fp_set;
                m_fp_get = p_fp_get;
            }
    
            inline operator TProperty(void)
            {
                return this->Get();
            }
    
            inline TProperty operator=(TProperty value)
            {
                this->Set(value);
            }
    };
    

    In your class where you wish to use it, you create a new field for the property, and you must call Init to pass your get/set methods to the property. (pref in .ctor).

    class MyClass {
    private:
        int _id;
    
        int getID() { return _id; }
        void setID(int newID) { _id = newID; }
    public:
        Property Id;
    
        MyClass() {
            Id.Init(this, &MyClass::getID, &MyClass::setID);
        }
    };
    

提交回复
热议问题