2013-04-27 46 views
0

我正在嘗試使用以下代碼。非模板參數爲什麼不能通過std :: vector

#include <iostream> 
#include <vector> 

using namespace std; 

template <typename T, std::vector <T> myV> 
int fun() 
{ 
    cout <<" Inside fun() "<<endl; 
} 

int main(int argc, char ** argv) 
{ 
    std::vector<int> a; 
    fun<int,a>(); 
} 

我無法通過的std ::矢量MYV?但

代替的std ::向量,我可以能夠使用類似模板 **,並樂趣()。

回答

0

你需要調用

fun<int, std::vector<int>>(); 

其傳遞std::vector<int>。如果你想傳遞的std::vector<int>一個實例(a),你將有你的函數定義修改爲:

template<typename T> 
int fun(std::vector<T> v) 
{ 
    std::cout << "Inside fun()\n"; 
} 

int main() 
{ 
    std::vector<int> a; 
    fun(a); 
} 
+0

很好解釋。 – Whoami 2013-04-27 10:59:51

1

什麼三角支架推移必須是一個類型或一個編譯時間常數;它不能是一個變量。雖然a的類型是vector<int>,a本身是vector<int>類型的對象;它不能作爲模板參數之一進入三角括號。

另外,不能使用vector<T>作爲模板函數的第二個參數:vector<T>是一種知道T後會變得完全知曉的類型。由於您已經有T作爲模板參數,因此您可以在函數內部「免費」地聲明vector<T>,而無需額外的模板參數。

最後,在C++ 11中,您可以使用decltype靜態獲取一個變量類型。例如,如果您修改代碼以利用T單一類型的參數,你可以這樣做:

#include <iostream> 
#include <vector> 

using namespace std; 

template <typename T> 
int fun() 
{ 
    cout <<" Inside fun() "<<endl; 
} 

int main(int argc, char ** argv) 
{ 
    std::vector<int> a; 
    // This is the same as calling fun<std::vector<int> >(); 
    fun<decltype(a)>(); 
    return 0; 
} 

Demo on ideone

+0

感謝您的回覆。是否有可能使用std :: vector 作爲模板參數?因爲std :: vector 本身就是一個數據類型吧?糾正我,如果我錯了。 – Whoami 2013-04-27 10:53:27

+0

@Whoami是的,可以使用'std :: vector '作爲模板參數:任何類型,包括基於模板的類型。你不能使用的是'std :: vector'(沒有''或其他類型的參數),因爲它是一個模板名稱,而不是一個類型。 – dasblinkenlight 2013-04-27 11:05:56

+0

所以,std :: vector是一個類模板,std :: vector 是它的專門化,它是一個有效的數據類型。如果我們仍然想提供std :: vector,那麼我們需要使用template-template參數的概念。是這樣嗎 ? – Whoami 2013-04-27 11:10:31

相關問題