C++ ReadOnly 与 C# Property—get

Posted on 2012-01-15 03:33  Anders  阅读(2260)  评论(0)    收藏  举报
1.ReadOnly in C#

ReadOnly Property在C#中的定义如下:

public int MyIntProp { getprivate set; }

 

 这段代码定义了一个只读的int类型字段:MyIntProp。

 2.ReadOnly in C++

在C++中要达到如此的效果,可以定义一个如下的ReadOnly类型:

 1     /**
 2      * readonly property
 3      */
 4     template<typename T>
 5     class ReadOnly
 6     {
 7     private:
 8 
 9         /**
10          * ptr to real data
11          */
12         const T & real_data;
13 
14     public:
15 
16         ReadOnly(const T & real_data_):real_data(real_data_){ }
17 
18         ReadOnly & operator=(const ReadOnly &)
19         {
20             //cout << "inside ReadOnly assignment operator" << endl;
21             return *this;
22         }
23 
24         operator const T &() 
25         {
26             return real_data;
27         }

28     }; 

 此段代码将一个字段包装成一个只读的属性,使用如下:

 ......

private:
    int _x;
public:
    ReadOnly<int> X;
  

    // aggregation readonly property and read data 

    MyConstructor()X(_x){};
......

 对外部访问者而言,只能看到x,且X无法修改。

但这还不够。

3. ReadOnly Property in C# advanced

考虑如下的C#代码:

 

1 public int MyIntValue
2 {
3     get
4     {
5        int x = 0;
6     // calculate return value x here
7     return x;    
8     }

9 }  

 

 这段代码中,MyIntValue的值是每次调用时实时计算的。这种情况下,上面的C++版本的ReadOnly就无法实现。

所以,我们需要下面的实现方式。

 

4.ReadOnly property in C++ advanced

在ReadOnly类中,加入对获取-调用-返回的过程的支持,代码如下:

 1     /**
 2      * readonly property implementation
 3      */
 4     template<typename T>
 5     class ReadOnly
 6     {
 7     private:
 8 
 9         /**
10          * ptr to read data
11          */
12         const T & real_data;
13 
14         bool _useFun;
15 
16         T(*_dataFunc)();
17     public:
18 
19         ReadOnly(const T & real_data_):real_data(real_data_),_useFun(false){ }
20 
21         ReadOnly(T(*ptr)()):real_data(NULL),_dataFunc(ptr),_useFun(true){}
22 
23         ReadOnly & operator=(const ReadOnly &)
24         {
25             //cout << "inside ReadOnly assignment operator" << endl;
26             return *this;
27         }
28 
29         operator const T &() 
30         {
31             if(!_useFun) return real_data;
32             return _dataFunc();
33         }

34     }; 

 

 通过这样的改造,现在可以像这样来使用ReadOnly了:

 1 #include "ReadOnly.h"
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 8 int myGetInt()
 9 {
10     cout<<"using function to get value!"<<endl;
11     return 10;
12 }
13 
14 int main()
15 {
16     ReadOnly<int> rop(myGetInt);
17     cout<<rop<<endl;

18 }

 5. summary

通过定义ReadOnly类,在C++中实现了类似于C# property-get的效果。目前我把它拿来作为让接口类看起来更“现代”的方式,希望对各位有所帮助。 

 

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