Search code examples
c++cudathrustnvcc

overloading an operator that has already been defined


I want to overload operator * but I keep getting function "operator*(int, int)" has already been defined. I'm using Thrust library and want to use my own * in my kernel.

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

Solution

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

    thrust::reduce offers you an opportunity to use your own binary operator in the reduction. The operator should be provided via a C++ functor.

    Here's a worked example showing the use of a binary operator to find the maximum value in a set of numbers:

    $ 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
    $