【问题标题】:Thrust reduce with tuple accumulator使用元组累加器减少推力
【发布时间】:2018-08-05 11:49:42
【问题描述】:

我想在thrust::host_vectorthrust::tuple<double,double> 上使用thrust::reduce。因为没有预定义的thrust::plus<thrust::tuple<double,double>>,所以我自己编写并使用了thrust::reduce 的变体,带有四个参数。

因为我是一个好公民,所以我将自定义版本的 plus 放在我自己的命名空间中,我没有定义主模板并将其专门用于 thrust::tuple<T...>

#include <iostream>
#include <tuple>

#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/tuple.h>

namespace thrust_ext {

namespace detail {

// https://stackoverflow.com/a/24481400
template <size_t ...I>
struct index_sequence {};

template <size_t N, size_t ...I>
struct make_index_sequence : public make_index_sequence<N - 1, N - 1, I...> {};

template <size_t ...I>
struct make_index_sequence<0, I...> : public index_sequence<I...> {};

template < typename... T, size_t... I >
__host__ __device__ thrust::tuple<T...> plus(thrust::tuple<T...> const &lhs,
                                             thrust::tuple<T...> const &rhs,
                                             index_sequence<I...>) {
    return {thrust::get<I>(lhs) + thrust::get<I>(rhs) ...};
}

} // namespace detail

template < typename T >
struct plus;

template < typename... T >
struct plus < thrust::tuple<T...> > {
    __host__ __device__ thrust::tuple<T...> operator()(thrust::tuple<T...> const &lhs,
                                                       thrust::tuple<T...> const &rhs) const {
        return detail::plus(lhs,rhs,detail::make_index_sequence<sizeof...(T)>{});
    }
};

} //namespace thrust_ext

int main() {
    thrust::host_vector<thrust::tuple<double,double>> v(10, thrust::make_tuple(1.0,2.0));

    auto r = thrust::reduce(v.begin(), v.end(),
                            thrust::make_tuple(0.0,0.0),
                            thrust_ext::plus<thrust::tuple<double,double>>{});

    std::cout << thrust::get<0>(r) << ' ' << thrust::get<1>(r) << '\n';
}

但是,这不会编译。错误消息非常长,请参阅this Gist。错误消息表明问题出在thrust::reduce 的某些实现细节中。另外,如果我用std::tuple 替换thrust::tuple,它会按预期编译和运行。

我正在使用 Thrust 1.8.1 和 Clang 6。

【问题讨论】:

    标签: c++ c++11 templates thrust


    【解决方案1】:

    正如您在错误消息中看到的,thrust::tuple&lt;double,double&gt; 实际上是 thrust::tuple&lt;double, double, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type, thrust::null_type&gt;

    这是一个基于默认模板参数的 C++03 风格的“可变参数模板”,这意味着 sizeof...(T) 将计算所有 null_types 并产生错误的大小(始终为 10)。

    您需要使用thrust::tuple_size 来检索实际大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2015-06-04
      • 2018-01-23
      • 2021-05-23
      • 2020-04-06
      • 1970-01-01
      相关资源
      最近更新 更多