C++ ReadOnly 与 C# Property—get (2)

Posted on 2012-01-15 05:58  Anders  阅读(603)  评论(0)    收藏  举报

 1.ReadOnly类的缺憾

前文中最后的ReadOnly类,在Class中并不能用,原因在于其初始化只接受全局的Function指针。而member function的调用必须使用隐式(?)的this指针。 

 

2.ReadOnlyFunc类

为了能在Class中使用ReadOnly并接受member function 作为计算结果的方法,建立了新的ReadOnlyFunc类。

他与ReadOnly类的最大区别在于其保存了一个指向“父”对象的this指针。在需要计算结果的时候,使用(_object->*_dataFunc)()来获得返回值。

ReadOnlyFunc实质上只是一个对member function的包装,与ReadOnly类关系不大。但为了保持定义成员变量时代码的一致性,沿用ReadOnlyXXXX的名称。 

 

 1     template<typename TC, typename TV>
 2     class ReadOnlyFunc
 3     {
 4     private:
 5 
 6         TV(TC::*_dataFunc)();
 7 
 8         TV _inner;
 9         TC* _object;
10     public:
11 
12         ReadOnlyFunc(TC *obj, TV (TC::*ptr)()):_object(obj),_dataFunc(ptr){}
13 
14         ReadOnlyFunc & operator=(const ReadOnlyFunc &)
15         {
16             return *this;
17         }
18 
19         operator const TV &() 
20         {
21             _inner = (_object->*_dataFunc)();
22             return _inner;
23         }

24     }; 

 

他拥有使用类成员函数来初始化并在需要时调用对象的方法计算结果的能力。

 

3.Sample

 测试代码如下:

 1 typedef int (*ifunc)();
 2 
 3 class MYMY
 4 {
 5 public:
 6     ReadOnlyFunc<MYMY,int> MyInt;
 7 
 8     MYMY():MyInt(this,&MYMY::cal){}
 9 
10     int cal()
11     {
12         cout<<"using function to get ReadOnly Property!"<<endl;
13         return 10;
14     }
15 };
16 
17 int myGetInt()
18 {
19     cout<<"using function to get ReadOnly!"<<endl;
20     return 10;
21 }
22 
23 int main()
24 {
25     ifunc myf = (ifunc)myGetInt;
26     ReadOnly<int> ro(myf);
27     cout<<ro<<endl;
28 
29     MYMY m1;
30     cout<<m1.MyInt<<endl;
34 } 

 

 所有代码在vc2010及gcc 4.6.2(g++ -fpermissive -std=c++0x)中编译通过。

测试结果如下:

 

1 using function to get ReadOnly!
2 10
3 using function to get ReadOnly Property!
4 10


4. ReadOnly 与 ReadOnlyFunc

通过使用这两个类,我们可以在C++中拥有C#类似的Property的能力。同时,由于屏蔽了更多地细节,对外部使用者而言也更加简洁。

这是一个使用的片段:

 

        ReadOnly<std::string> Address;
        ReadOnlyFunc<MultiMessage,size_t> Count;

        XXXXXX()
            :    _address(""),Address(_address),
            Count(this,&XXXXXX::calCount)
......... 

 

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3