2010年7月15日 星期四

[C++] How to implement property in C++

Introduction

In the past, I used property to develop .NET program frequently.
But in Java or C++, I must use get/set method to access private member in Object-Oriented Programming.
I like to use property not get/set method!

Background

Startand C++ dose not support property statement, so programmers need to declare get/set method to access private member.
First programmers should understand template and function point.
I found a sample code from google, that use template and function point to solve type and access get/set method.
This solution is not good, because use a class and function point to access will reduce performance.
Directly use get/set method is better.

Source Code
template<class _Prop_t,class _ObjClass_t>
class Property
{
private:
typedef _Prop_t (_ObjClass_t::* _pmGet_t)() const;
typedef void (_ObjClass_t::* _pmSet_t)(_Prop_t);

_ObjClass_t& m_objInstance;
_pmGet_t m_pmGet;
_pmSet_t m_pmSet;

public:
Property(_ObjClass_t& objInstance, _pmGet_t pmGet, _pmSet_t pmSet)
: m_objInstance(objInstance), m_pmGet(pmGet), m_pmSet(pmSet)
{}
operator _Prop_t() { return (_Prop_t)(m_objInstance.*m_pmGet)(); }
void operator =(_Prop_t value) { (m_objInstance.*m_pmSet)(value); }
};



Download
Sample Code

2 則留言:

  1. Thanks for this post, property software save our hours of work and administrative frustration on our daily property management tasks.

    回覆刪除

Hello