实现C++“属性”:模板实现

属性的基本特征就是拥有getter、setter。

C++中基本上把实现一个类的赋值运算符、类型转换运算符就能实现属性的特征,而在类型方面,使用模板便可以处理任意类型:

namespace extension
{

    template<typename T> struct property
    {
    protected:

    public:
        property() = default;
        property(const property<T>& _pt) : __t(_pt) {}
        property(property<T>&& _pt) noexcept : __t(_pt) {}
        property(const T& _t) : __t(_t) {}
        property(T&& _t)noexcept : __t(_t) {}
        T& operator=(const T& _t) 
        { 
            __t = _t;
            return __t;
        }
        T& operator=(T&& _t) noexcept { 
            __t = _t; 
            return __t;
        }
        T& operator=(const property<T>& _t)
        {
            __t = _t;
            return __t;
        }
        T& operator=(property<T>&& _t) noexcept {
            __t = _t;
            return __t;
        }
        operator T() const { return __t; }

    private:
        T __t;
    };
    
}
struct MyStruct
{
    property<int> num = 9;
};



int main()
{
    MyStruct ms;
    cout << ms.num << endl;
    ms.num = 10;
    cout << ms.num << endl;
    
    property<int> i = 90;
    ms.num = i;
    cout << ms.num << endl;
    property<int> y(i);
    cout << y << endl;

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容