瀏覽單個文章
學長壞壞
Basic Member
 
學長壞壞的大頭照
 

加入日期: Jun 2012
您的住址: ?????
文章: 12
C++ 定義特殊化樣版

請問關於C++ 定義特殊化樣版的問題
使用Dev-C++ 5.11
原始碼如下:

#include <iostream>
#include <iomanip>
using namespace std;

template<class T> T larger(T a, T b);
template<> long* larger<long*>(long* a, long* b);

int main()
{
cout << endl;
cout << "Larger of 1.5 and 2.5 is " << larger(1.5, 2.5) << endl;
cout << "Larger of 3.5 and 4.5 is " << larger(3.5, 4.5) << endl;

int value1 = 35;
int value2 = 45;

cout << "Larger of " << value1 << " and " << value2 << " is "
<< larger(value1, value2)
<< endl;

int a = 9;
int b = 8;
cout << "Larger of " << a << " and " << b << " is "
<< larger(a,b)
<< endl;

cout << "Larger of " << a << " and " << b << " is "
<< *larger(&a, &b)
<< endl;

return 0;
}

template<class T> T larger(T a, T b)
{
cout << "standard version " << endl;
return a>b ? a : b;
}

template<> long* larger<long*>(long* a, long* b)
{
cout << "specialization version " << endl;
return *a>*b ? a : b;
}

預期的結果是:
standard version
Larger of 1.5 and 2.5 is 2.5
standard version
Larger of 3.5 and 4.5 is 4.5
standard version
Larger of 35 and 45 is 45
standard version
Larger of 9 and 8 is 9
specializationd version
Larger of 9 and 8 is 9

實際的結果是:
standard version
Larger of 1.5 and 2.5 is 2.5
standard version
Larger of 3.5 and 4.5 is 4.5
standard version
Larger of 35 and 45 is 45
standard version
Larger of 9 and 8 is 9
standard version
Larger of 9 and 8 is 9


請問為何不能使用特殊化樣版?
謝謝!
     
      
舊 2021-07-19, 09:51 PM #1
回應時引用此文章
學長壞壞離線中