I am trying to achieve a very simple thing using C++ templates. I would like to build a generic sign function that could handle the case sgn(x)where x could be either doubleor std::vector<double> (that is returning a std::vector<double> containing the results). 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>. Unfortunately my function does not use any arithmetic operator and the conditional operator cannot be overloaded. How should I proceed ?
While overloading is the best way to achieve what you want, it is not
really the way to work with the C++ standard library.
If you want to apply a function to all elements of a container (either
mutating them or creating new results), use
std::transformorstd::for_eachwith the function you want to use.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.