#include<iostream>
#include<algorithm>
using namespace std;
template<typename ResultFunction,typename Function>
ResultFunction function_cast(Function fun)
{
ResultFunction result=ResultFunction(*(reinterpret_cast<int*>(&fun)));
return result;
}
template<typename R,typename ClassType,typename Function>//,typename Function
class method_property_set
{
public:
typedef void (*hook_function)(ClassType *ptr);
hook_function set_fun,get_fun;
ClassType *obj;
method_property_set(ClassType *ptr,Function set,Function get):obj(ptr)
{
set_fun=function_cast<void (*)(ClassType*)>(set);
get_fun=function_cast<void (*)(ClassType*)>(get);
}
operator R () const
{
get_fun(obj);
return m_value;
}
int m_value;
method_property_set<R,ClassType,Function> operator =(int value)
{
set_fun(obj);
m_value=value;
}
};
class Container
{
public:
method_property_set<int,Container,void (Container::*)() > Prop;
Container():Prop(this,&Container::SetValue,&Container::GetValue){}
private:
void SetValue()
{
cout<<"set the value of Prop"<<endl;
}
void GetValue()
{
cout<<"get the value of Prop"<<endl;
}
void SomeMethod()
{
int pr_val = Prop; // Uses the implicit conversion operator
//cout<<"the value of pr_val:"<<pr_val<<endl;
}
};
int main()
{
Container con;//自动调用函数GetValue();
con.Prop=100;//自动调用SetValue();
cout<<"output the property of Prop:"<<con.Prop<<endl;
}
该程序改编自imperfect C++中part six,Chapter 35. Properties中的程序,程序经gcc编译运行顺利。
以上程序要将成员函数指针转换为非成员函数指针,会对程序的运行效率有影响。以下是另一版本的method_property_set类。
template<typename R,typename ClassType,typename Function>//,typename Function
class method_property_set
{
public:
typedef void (ClassType::*HookFunction)();
HookFunction set_fun,get_fun;
ClassType *obj;
method_property_set(ClassType *ptr,Function set,Function get):obj(ptr)
{
set_fun=set;
get_fun=get;
}
operator R () const
{
(obj->*get_fun)();
return m_value;
}
int m_value;
method_property_set<R,ClassType,Function> operator =(int value)
{
(obj->*set_fun)();
m_value=value;
}
};