重载已定义的运算符

overloading an operator that has already been defined

我想重载运算符 * 但我一直收到函数 "operator*(int, int)" 已经定义。我正在使用 Thrust 库并想在我的内核中使用我自己的 *。

 __device__ int operator*(int x, int y)
{
    int value = ...                                    
    return value;                                     
}

What I want to do is to use Thrust's reduction with my own * operator

thrust::reduce为您提供了一个use your own binary operator减价的机会。运算符应通过 C++ 仿函数提供。

下面是一个示例,展示了如何使用二元运算符查找一组数字中的最大值:

$ cat t1093.cu
#include <thrust/device_vector.h>
#include <thrust/reduce.h>
#include <iostream>

const int dsize = 10;

struct max_op
{
template <typename T>
  __host__ __device__
  T operator()(const T &lhs, const T &rhs) const
  {
    return (lhs>rhs)?lhs:rhs;
  }
};

int main(){

   thrust::device_vector<int> data(dsize, 1);
   data[2] = 10;
   int result = thrust::reduce(data.begin(), data.end(), 0, max_op());
   std::cout << "max value: " << result << std::endl;
   return 0;
}
$ nvcc -o t1093 t1093.cu
$ ./t1093
max value: 10
$