[英]Nested C++ templates
我有一个名为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));
}
请注意,我将in
和c
参数更改为const &
-因为它们仅是输入参数,因此您不希望(能够)在函数内部对其进行修改。 并将它们作为const &
允许传入临时变量,这对于非const引用是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.