C++에서 프로퍼티 구현하기 #
C++에서 템플릿을 이용한 프로퍼티를 구현한 소스입니다.
VC++에서는 프로퍼티를 컴파일러 차원에서 지원하지만 이건 ANSI 코드입니다.
VC++에서는 프로퍼티를 컴파일러 차원에서 지원하지만 이건 ANSI 코드입니다.
출처는 BorlandForum 이고 보다 안정적이게 소스를 수정했습니다.
#ifndef __PROP_H__BY_CDECL__
#define __PROP_H__BY_CDECL__
namespace Glass {
class IYES {};
class YES : public IYES {};
class NO {};
template <class T, class Parent, class ReadWrite = YES>
class Prop
{
public:
typedef Prop<T, Parent> this_type;
typedef T (Parent::*get_fun)();
typedef void (Parent::*set_fun)(const T&);
Prop() : getf_(NULL), setf_(NULL), parent_(NULL) {}
void SetParent(Parent *p) {
parent_ = p;
}
void Set(set_fun f) {
ReadWrite yn;
IYES *p = &yn; // 읽기전용일때 이함수를 사용하면 컴파일 에러 !!
setf_ = f;
}
void Get(get_fun f) {
getf_ = f;
}
T operator=(const T &value) {
ReadWrite yn;
IYES *p = &yn; // 읽기전용일때 이함수를 사용하면 컴파일 에러 !!
if (!setf_) {
throw exception();
}
(parent_->*setf_)(value);
return value;
}
T operator=(this_type &type) {
return operator=(static_cast<T>(type));
}
operator T() {
if (!getf_) {
throw exception();
}
return (parent_->*getf_)();
}
private:
Parent *parent_;
get_fun getf_;
set_fun setf_;
};
} // namespace Glass
#endif // __PROP_H__BY_CDECL__
#include <iostream>
#include <string>
using namespace std;
class AA
{
public:
AA() {
Str.SetParent(this);
Str.Set(&AA::setStr);
Str.Get(&AA::getStr);
}
void setStr(const string &str)
{
cout << "setStr" << endl;
str_ = str;
}
string getStr()
{
cout << "getStr" << endl;
return str_;
}
Glass::Prop<string, AA> Str;
string str_;
};
int main()
{
AA a;
a.Str = "cdecl ";
}
'Dev > C++' 카테고리의 다른 글
| memory pooling - code (0) | 2008.05.01 |
|---|---|
| Is Derived - code (0) | 2008.05.01 |
| boost::pool 예제 (0) | 2008.05.01 |
| STLport 초간단 설치 (1) | 2008.05.01 |
| Stroustrup - The real interview (0) | 2008.05.01 |