2

私は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ましたが、うまくいきませんでした。

ベクトルの型とベクトル反復+子の型の両方で演算子をオーバーロードする方法がわかりません。これは理にかなっていますか?

ご協力いただきありがとうございます!

4

1 に答える 1

2

これはうまくいくようですが、他の人はより良いアイデアを持っているかもしれません:

#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::transformまた、テンプレート定義に含まれていた関数パラメーターが正しくないことに注意してください。

于 2013-06-03T23:35:59.123 に答える