简体   繁体   English

使用向量而不是将double用作输入时的模板

[英]Templates when using vectors instead of doubles as input

I am trying to achieve a very simple thing using C++ templates. 我正在尝试使用C ++模板实现非常简单的事情。 I would like to build a generic sign function that could handle the case sgn(x) where x could be either double or std::vector<double> (that is returning a std::vector<double> containing the results). 我想构建一个通用的符号函数,以处理sgn(x)的情况,其中x可以是doublestd::vector<double> (这将返回包含结果的std::vector<double> )。 In order to achieve that I am using templates 为了实现我正在使用模板

double f(double x) {
    return (x>=0)?1.0:-1.0;
};

template<typename T>
T F(T x) {
   // ?
};

I would like to cast the template and either use f if double or a for loop if std::vector<double> . 我想转换模板,如果是double使用f ,或者如果std::vector<double>则使用for循环。 Unfortunately my function does not use any arithmetic operator and the conditional operator cannot be overloaded. 不幸的是,我的函数没有使用任何算术运算符,并且条件运算符无法重载。 How should I proceed ? 我应该如何进行?

This is solved by overloading, not templates. 这是通过重载而不是模板来解决的。

double sign(double x) {
    return x < 0.0 ? -1.0 :
           x > 0.0 ?  1.0 : 0.0;
};

std::vector<double> sign(std::vector<double> const& x) {
    // ?
};

That said, I'd doubt whether a sign function is meaningful for vectors. 就是说,我怀疑sign函数对矢量是否有意义。

This, by the way, has got nothing to do with “arithmetic” versus “non-arithmetic” functions, as alleged in the title of the question. 顺便说一下,这与问题标题中所说的“算术”与“非算术”功能无关。 This distinction doesn't exist in C++. 这种区别在C ++中不存在。

While overloading is the best way to achieve what you want, it is not really the way to work with the C++ standard library. 重载是实现所需目标的最佳方法,但实际上并不是使用C ++标准库的方法。

If you want to apply a function to all elements of a container (either mutating them or creating new results), use std::transform or std::for_each with the function you want to use. 如果要对容器的所有元素应用函数(对它们进行突变或创建新结果),请对要使用的函数使用std::transformstd::for_each

std::vector<double> doubles, results;
std::transform(begin(doubles), end(doubles), std::back_inserter(results), sgn);

That separates concern far better than your current approach. 与当前方法相比,这将关注点分离得更好。 Only operate on whole containers if it is really required, in all other cases use iterators and higher-order functions. 仅在确实需要时才对整个容器进行操作,在所有其他情况下,请使用迭代器和高阶函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM