嵌套的C 模板

Nested C++ templates

本文关键字:模板 嵌套      更新时间:2023-10-16

i具有一个称为 add_vector_to_scalar的函数,该函数将标量值添加到向量(in),并将结果存储在另一个向量(out)中。我正在学习C ,所以我不确定如何将add_op generic的类型参数制作?我考虑过添加另一个打字机T,但它不起作用。

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

向量可能是两种类型:

device_vector<T>
host_vector<T>

add_op结构看起来像这样:

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;
    }
};

简单地制作 T 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));   
}

请注意,我更改了inc参数为const &-由于它们仅输入参数,因此您不想(能够)在功能中修改它们。并将它们作为const &允许传递临时性,而非const引用是不可能的。