2014-01-29 61 views
1

這與previous question I asked類似,但它涉及模板矢量分量相加功能。表示嵌套的C++模板

我有一個叫做add的函數,它需要兩個向量並將它們的相加存儲在輸出向量中。我正在學習C++,所以我不知道如何使類型參數爲thrust::plus通用?問題是Tdevice_vectorhost_vector的類型參數;這應該是Vector的類型參數。

template<typename Vector, typename T> 
void add(const Vector& in1, const Vector& in2, Vector& out) { 
    transform(in1.begin(), in1.end(), in2.begin(), out.begin(), thrust::plus<T>(c)); 
} 

的載體可以是兩個類型:

device_vector<T> 
host_vector<T> 

我的代碼不能編譯,因爲它是在抱怨:

error: no instance of function template "add" matches the argument list 

我怎麼能起到加功能通用的,所以它很容易與Tdevice_vector<T>host_vector<T>一起使用?

回答

3

使用容器的value_type,並去除第二模板參數,因爲它不能推斷出:

template<typename Vector> 
void add(const Vector& in1, const Vector& in2, Vector& out) { 
transform(in1.begin(), in1.end(), in2.begin(), out.begin(), 
      thrust::plus<typename Vector::value_type>(c)); 
} 
+0

完美。它現在可以工作,所以謝謝你。我來自Java,所以泛型系統與我習慣的有所不同。 – jimjampez

+2

@jimjampez C++模板與Java泛型完全不同,所以你可能會「忘掉你學到的東西」,至少暫時:) – juanchopanza

+0

大聲笑:)你有書推薦爲Java開發人員學習C++嗎? – jimjampez

1

請教thrust::host_vector的文檔,看它是否提供了一種嵌套的typedef其模板參數(如std::vector<T>提供了與T相同的std::vector<T>::value_type)。如果有,請使用它(如@ juanchopanza的答案所示)。但是,我試圖簡單地看一下推力文檔,他們沒有列出這樣的typedef(不幸和令人驚訝的,但也許是真的)。如果確實沒有提供它,你必須使用一個模板,模板參數,而不是:

template<template <typename T, typename A> class Vector> 
void add(const Vector<T, A>& in1, const Vector<T, A>& in2, Vector<T, A>& out) { 
    transform(in1.begin(), in1.end(), in2.begin(), out.begin(), thrust::plus<T>(c)); 
} 

請注意,你不能只用T爲模板模板paremeter,你要反映預期輸入的實際模板參數類模板。在C++ 11中,您可以通過使用可變模板來幫助自己:

template<template <typename T, typename... Other> class Vector> 
void add(const Vector<T, Other...>& in1, const Vector<T, Other...>& in2, Vector<T, Other...>& out) { 
    transform(in1.begin(), in1.end(), in2.begin(), out.begin(), thrust::plus<T>(c)); 
} 
+0

我實際上找到了'value_type'的定義,例如參見[here](http://docs.thrust.googlecode.com/hg/host__vector_8h_source.html)。 – juanchopanza

+0

@juanchopanza這很好(合理)。谷歌把我帶到一些不相關的文檔,或者他們沒有記錄它們提供typedefs。 – Angew