兩段想當(dāng)然寫下的代碼,你看出問題了吧
1 class Data;
2 Data* FindData();
3 void GetData(Data* dataPtr)
4 {
5 dataPtr=FindData();
6 }
7 Data* data=NULL;
8 GetData(data);
9 data->somefunction();
第二段代碼,更得仔細點
1 class A;
2 class B;
3 A const * GetA();
4 B const * GetB();
5 template<typename T>
6 int GetSpecialValue(T* classPtr)
7 {
8 return 3721;
9 }
10
11 template<>
12 int GetSpecialValue<>(A* classPtr)
13 {
14 return 37;
15 }
16 template<>
17 int GetSpecialValue<>(B* classPtr)
18 {
19 return 21;
20 }
21 A const * classPtr=GetA();
22 int ret=GetSpecialValue(classPtr);
23 cout<<ret<<endl; //out 3721! why not 37?
24
25
26
第一段的問題在于看到指針想當(dāng)然認為是地址,data 可以帶回反回值,其實因為這里是值傳遞,實參data把自己的值賦給了dataPtr,dataPtr后來確實從FindData()得到了想要的值,但這對一點影響也沒有,所以函數(shù)返回時,data的值沒有發(fā)生變化,也就是沒有帶回想要的值。
只要不想當(dāng)然,仔細一想就明白了,解決辦法很簡單:
1 void GetData(Data*& dataPtr)
2 4 {
3 5 dataPtr=FindData();
4 6 }
第二段的問題是沒有注意到那個const, T* 和 T const* 是不一樣的,不能完全匹配,所以不會找到對A類型的特化版本,解決辦法可以這樣:
1 template<typename T>
2 int GetSpecialValue(T const* classPtr)
3 {
4 return 3721;
5 }
6
7 template<>
8 int GetSpecialValue<>(A const* classPtr)
9 {
10 return 37;
11 }
12 template<>
13 int GetSpecialValue<>(B const* classPtr)
14 {
15 return 21;
16 }
能過這兩個小例子就可以知道,C++細節(jié)很多,要仔細,不能想當(dāng)然。
posted on 2009-05-06 21:09
清源游民 閱讀(1755)
評論(5) 編輯 收藏 引用 所屬分類:
C++