原文地址在这:http://www.cnblogs.com/feng-sc/p/5742689.html
实现挺有意思的,看懂了代码也可以加深对C++知识的理解,是不错的小技巧,记录下来。
#include<functional> #define property_setter(variableType) [&](variableType value) #define property_getter(variableType) [&]()->variableType template <typename ValueType> class property_rw { public: typedef std::function<void(ValueType value)> Setter; typedef std::function<ValueType(void)> Getter; explicit property_rw(Setter setter, Getter getter) : m_setter(setter), m_getter(getter) {} property_rw& operator=(ValueType value) { this->value = value; m_setter(this->value); return *this; } property_rw& operator=(const property_rw & instance) { this->value = instance.m_getter(); m_setter(this->value); return *this; } operator ValueType() { return m_getter(); } private: ValueType value; Setter m_setter; Getter m_getter; }; template <typename ValueType> class property_r { public: typedef std::function<void(ValueType value)> Setter; typedef std::function< ValueType (void)> Getter; explicit property_r(Getter getter) : m_getter(getter) {} operator ValueType() { return m_getter(); } private: ValueType value; Getter m_getter; }; template <typename ValueType> class property_w { public: typedef std::function <void(ValueType value)> Setter; explicit property_w(Setter setter) : m_setter(setter) {} property_w& operator=(ValueType value) { this->value = value; m_setter(this->value); return *this; } property_w& operator=(const property_w & instance) { this->value = instance.m_getter(); m_setter(this->value); return *this; } private: ValueType value; Setter m_setter; }; #include <iostream> #include <string> #include "test.h" using namespace std; class TestDemo { public: property_rw<string> Name = property_rw<string>( property_setter(std::string) { m_rw_name = value; }, property_getter(std::string) { return m_rw_name; } ); property_r<string> ReadOnlyName = property_r<string>( property_getter(std::string) { return m_readonly_name; } ); property_w<string> WriteOnlyName = property_w<string>( property_setter(std::string) { m_writeonly_name = value; TestWork(); } ); void TestWork() { std::cout <<"TestWork()::m_writeonly_name--" << std::endl; } private: std::string m_rw_name; std::string m_readonly_name = "I m read only name"; std::string m_writeonly_name = ""; }; int _tmain(int argc, _TCHAR* argv[]) { TestDemo test; test.Name = "This is test name!"; std::string str = test.Name; std::string readonly = test.ReadOnlyName; std::cout<< "Test read and write,Name:" <<str<< std::endl; std::cout<< "Test readonly, msg:"<< readonly << std::endl; test.WriteOnlyName = "This is write only property!"; //test.ReadOnlyName = "This is write only property!"; //std::string s = test.WriteOnlyName; return 0; }