Вопрос

I have a function called add_vector_to_scalar which adds a scalar value to a vector (in) and stores the result in another vector (out). I am learning C++ so I am not sure how to make the type parameter to add_op generic? I thought about adding another typename T but it did not work.

template<typename Vector>
void add(Vector& in, Vector& out, T& c) {
    transform(in.begin(), in.end(), out.begin(), add_op<int>(c));   
}

The vector could be of two type:

device_vector<T>
host_vector<T>

The add_op struct looks like this:

template<typename T>
struct add_op : public thrust::unary_function<T,T> {
    const T c;  

    add_op(T v) : c(v) {}

    __host__ __device__
    T operator()(const T x) {
        return x + c;
    }
};
Это было полезно?

Решение

Simply make T another template parameter of add_vector_to_scalar:

template<typename Vector, typename Scalar>
void add(const Vector& in, Vector& out, const Scalar& c) {
    transform(in.begin(), in.end(), out.begin(), add_op<Scalar>(c));   
}

Note that I changed the in and c parameters to be taken as const & - as they're input-only parameters, you don't want to (be able to) modify them inside the function. And taking them as const & allows temporaries to be passed in, which is not possible with non-const references.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top