2016-02-28 40 views
1

我想重載運算符*,但我不斷收到函數「operator *(int,int)」已經定義。我正在使用Thrust庫,並希望在我的內核中使用我自己的*。重載已定義的運算符

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

什麼是編譯器? – Nik

+0

@IlDivinCodino我正在使用NVCC – Mems

+1

如何在純C++中執行此操作?你能給個例子嗎?運算符是否重載[需要某種類的類定義](https://isocpp.org/wiki/faq/intrinsic-types#intrinsics-and-operator-overloading)?要麼操作符重載必須是類成員函數,要麼操作符重載必須將類作爲其參數之一? –

回答

2

我想要做的是減少使用推力的降低與我自己的運算符*

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

非常感謝。我可以爲CUB做同樣的事嗎?我試圖以同樣的方式定義我自己的操作員掃描Cub,但沒有奏效。 – Mems

+1

對於某些算法實現,您可以在CUB中執行類似的操作。在[cub文檔](https://nvlabs.github.io/cub/structcub_1_1_device_reduce.html#)中提供了用於將最少運算符(非常類似於上面的max運算符)傳遞給'cub :: DeviceReduce :: Reduce'的示例代碼。 aa4adabeb841b852a7a5ecf4f99a2daeb)。它也可以爲'cub :: DeviceScan :: InclusiveScan'完成,示例代碼在這裏提供(https://nvlabs.github.io/cub/structcub_1_1_device_scan.html#af27a73a9a8daef1b4fe5a16233932e30)。 –

+0

我試過CUB自定義運算符的例子,它的工作原理,但問題是它只是爲塊大小的數組工作;。這少於1024個元素。我正在使用DeviceScan,但它始終掛起以用於較大的輸入。 – Mems