2013-05-12 156 views
7

我正在學習C++模板概念。我不明白以下內容。如何將數組傳遞給函數模板以供參考

#include <iostream> 
#include <typeinfo> 

using namespace std; 

template <typename T> 
T fun(T& x) 
{ 
cout <<" X is "<<x; 
cout <<"Type id is "<<typeid(x).name()<<endl; 
} 


int main (int argc, char ** argv) 
{ 
    int a[100]; 
    fun (a); 
} 

我在想什麼?

1)T的樂趣(T & X)

這裏x是一個參考,因此將不腐朽 'A' 到指針類型,但 在編譯時,我得到下面的錯誤。

error: no matching function for call to ‘fun(int [100])’ 

當我嘗試非參考,它工作正常。據我所知,這個數組被腐蝕成指針類型。

回答

16

C樣式數組是非常基本的構造,它們不能以內建或用戶定義類型的方式分配,複製或引用。爲了實現通過引用傳遞數組相當於,你需要的語法如下:

// non-const version 
template <typename T, size_t N> 
void fun(T (&x)[N]) { ... } 

// const version 
template <typename T, size_t N> 
void fun(const T (&x)[N]) { ... } 

注意,這裏的數組的大小也是一個模板參數,使函數工作將所有的數組的大小,因爲T[M]T[N]對於不同的M,N不是相同的類型。還要注意該函數返回void。沒有辦法按值返回數組,因爲該數組不可複製,如前所述。

4

問題在於返回類型:由於數組不可返還,因此無法返回數組。順便說一句,你什麼都沒有返回!

嘗試,而不是:

template <typename T> 
void fun(T& x) // <--- note the void 
{ 
    cout <<" X is "<<x; 
    cout <<"Type id is "<<typeid(x).name()<<endl; 
} 

和預期的一樣,將工作。

注:原來完整的錯誤信息(用gcc 4.8)居然是:

test.cpp: In function ‘int main(int, char**)’: 
test.cpp:17:10: error: no matching function for call to ‘fun(int [100])’ 
    fun (a); 
    ^
test.cpp:17:10: note: candidate is: 
test.cpp:7:3: note: template<class T> T fun(T&) 
T fun(T& x) 
^
test.cpp:7:3: note: template argument deduction/substitution failed: 
test.cpp: In substitution of ‘template<class T> T fun(T&) [with T = int [100]]’: 
test.cpp:17:10: required from here 
test.cpp:7:3: error: function returning an array 

最相關的信息是最後一個。

+0

「有效的現代C++」中的第1項也提供了這種方式。編寫'(&param)[N]'是多餘的,除非你需要在'f'的主體中引用'N'(即使這個類型也可以推導出來) – 2014-12-24 08:26:26

相關問題