C++ 表示嵌套的C++;模板
这类似于,但它涉及一个模板化向量分量加法函数 我有一个名为C++ 表示嵌套的C++;模板,c++,vector,cuda,thrust,C++,Vector,Cuda,Thrust,这类似于,但它涉及一个模板化向量分量加法函数 我有一个名为add的函数,它接受两个向量并将它们的加法存储在输出向量中。我正在学习C++,所以我不知道如何使类型参数为推力::问题是T是device_vector和host_vector的类型参数;它应该是向量的类型参数 template<typename Vector, typename T> void add(const Vector& in1, const Vector& in2, Vector& out)
add
的函数,它接受两个向量并将它们的加法存储在输出向量中。我正在学习C++,所以我不知道如何使类型参数为<代码>推力::问题是T
是device_vector
和host_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));
}
如何播放plus函数generic,使其能够轻松使用设备向量
或主机向量
的T
?使用容器的值类型
,并删除第二个模板参数,因为无法推断:
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));
}
模板
void add(常量向量&in1,常量向量&in2,向量&out){
转换(in1.begin()、in1.end()、in2.begin()、out.begin(),
推力::加(c));
}
使用容器的值\u类型
,删除第二个模板参数,因为无法推断:
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));
}
模板
void add(常量向量&in1,常量向量&in2,向量&out){
转换(in1.begin()、in1.end()、in2.begin()、out.begin(),
推力::加(c));
}
查阅推力::主机_向量
的文档,查看它是否为其模板参数提供嵌套的typedef(例如std::向量
提供与T
相同的std::向量_类型
)。如果有,就使用它(如@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));
}
查阅stress::host_vector
的文档,查看它是否为其模板参数提供了嵌套的typedef(例如std::vector
提供了与T
相同的std::vector::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));
}
完美的现在可以了,谢谢你。我来自java java java系统,所以泛型系统和我以前习惯的有点不同。@ JimJAMPEZ C++模板与Java泛型完全不同,所以你也可以“不学你学过的东西”,至少暂时地说:LOL:你有没有一本书推荐给Java开发者学习C++?看看,太好了。现在可以了,谢谢你。我来自java java java系统,所以泛型系统和我以前习惯的有点不同。@ JimJAMPEZ C++模板与Java泛型完全不同,所以你也可以“不学你学过的东西”,至少暂时地说:LOL:你有没有一本书推荐给Java开发者学习C++?看一看。我实际上找到了value\u类型
定义,例如,请参阅。@juanchopanza这很好(也很合理)。要么谷歌带我去看一些不相关的文档,要么他们提供了typedef而没有对它们进行文档化。我实际上找到了value\u type
定义,例如。@juanchopanza这很好(也很合理)。要么谷歌把我带到了一些不相关的文档,要么他们提供了typedef而没有记录它们。
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));
}