推力的"+"运算符过载,有什么想法吗?
Overloading "+" operator for Thrust, any ideas?
我正在使用CUDA和Thrust。我发现输入thrust::transform [plus/minus/divide]
很乏味,所以我只想重载一些简单的操作符。
如果我能做到:
thrust::[host/device]_vector<float> host;
thrust::[host/device]_vector<float> otherHost;
thrust::[host/device]_vector<float> result = host + otherHost;
下面是+
的示例代码片段:
template <typename T>
__host__ __device__ T& operator+(T &lhs, const T &rhs) {
thrust::transform(rhs.begin(), rhs.end(),
lhs.begin(), lhs.end(), thrust::plus<?>());
return lhs;
}
然而,thrust::plus<?>
没有正确过载,或者我没有正确地做它…一个或另一个。(如果重载简单操作符是一个坏主意,请解释原因)。最初,我认为我可以用typename T::iterator
之类的东西重载?
占位符,但这不起作用。
我不确定如何用vector 的类型和vector迭代器的类型重载+
操作符。这有道理吗?
谢谢你的帮助!
这似乎有效,其他人可能有更好的主意:
#include <ostream>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/functional.h>
#include <thrust/copy.h>
#include <thrust/fill.h>
#define DSIZE 10
template <typename T>
thrust::device_vector<T> operator+(thrust::device_vector<T> &lhs, const thrust::device_vector<T> &rhs) {
thrust::transform(rhs.begin(), rhs.end(),
lhs.begin(), lhs.begin(), thrust::plus<T>());
return lhs;
}
template <typename T>
thrust::host_vector<T> operator+(thrust::host_vector<T> &lhs, const thrust::host_vector<T> &rhs) {
thrust::transform(rhs.begin(), rhs.end(),
lhs.begin(), lhs.begin(), thrust::plus<T>());
return lhs;
}
int main() {
thrust::device_vector<float> dvec(DSIZE);
thrust::device_vector<float> otherdvec(DSIZE);
thrust::fill(dvec.begin(), dvec.end(), 1.0f);
thrust::fill(otherdvec.begin(), otherdvec.end(), 2.0f);
thrust::host_vector<float> hresult1 = dvec + otherdvec;
std::cout << "result 1: ";
thrust::copy(hresult1.begin(), hresult1.end(), std::ostream_iterator<float>(std::cout, " ")); std::cout << std::endl;
thrust::host_vector<float> hvec(DSIZE);
thrust::fill(hvec.begin(), hvec.end(), 5.0f);
thrust::host_vector<float> hresult2 = hvec + hresult1;
std::cout << "result 2: ";
thrust::copy(hresult2.begin(), hresult2.end(), std::ostream_iterator<float>(std::cout, " ")); std::cout << std::endl;
// this line would produce a compile error:
// thrust::host_vector<float> hresult3 = dvec + hvec;
return 0;
}
注意,在这两种情况下,我都可以为结果指定主机或设备向量,因为thrust将看到差异并自动生成必要的复制操作。因此,我的模板中的结果向量类型(主机,设备)并不重要。
还要注意,模板定义中的thrust::transform
函数参数不太正确。
相关文章:
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 这里的 = 运算符有什么用法?
- unique_ptr < 0 或小于运算符做什么?
- "operator()"在重载运算符方法中是什么意思,在priority_queue(STL)中用作C++中的比较器?
- 是什么让一些命名函数/运算符与众不同?
- C++,()运算符重载,它的工作是什么
- 提供运算符+或运算符到双向迭代器有什么缺点吗?
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 在C++中,运算符 sizeof 返回什么数据类型?
- 运算符++();调用和++(*this)有什么区别?
- 第二个常量在运算符函数中做什么?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 当值传递给C++中的运算符重载函数时会发生什么
- 除了调用全局删除运算符之外,删除一个void指针还能做什么呢
- 在复制构造函数中放入什么 = 运算符重载
- 什么C++运算符在这里被重载了
- 当类作为参数传递给printf()时,要重载什么运算符
- 如果我想使用什么运算符" a = {x, y};"