[英]Nested C++ templates
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
). 我有一个名为
add_vector_to_scalar
的函数,该函数将标量值添加到向量中( in
)并将结果存储在另一个向量中( out
)。 I am learning C++ so I am not sure how to make the type parameter to add_op generic
? 我正在学习C ++,所以不确定如何将类型参数设为
add_op generic
? I thought about adding another typename T
but it did not work. 我考虑过添加另一个类型名称
T
但是它没有用。
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: 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;
}
};
Simply make T
another template parameter of add_vector_to_scalar
: 只需将
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));
}
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. 请注意,我将
in
和c
参数更改为const &
-因为它们仅是输入参数,因此您不希望(能够)在函数内部对其进行修改。 And taking them as const &
allows temporaries to be passed in, which is not possible with non-const references. 并将它们作为
const &
允许传入临时变量,这对于非const引用是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.