C++中实现C#属性相似的语法

#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;
  }
};


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值