I am writing function templates to work with float, double, std::complex<float>, and std::complex<double> types.
I often need to declare a type that corresponds to "same precision but purely real". So both float and std::complex<float> would map to float, etc.
I've been doing this with an overload like:
template <typename numeric_t, typename real_t>
numeric_t foo(numeric_t x) {
real_t y = abs(x);
return x/y;
}
template <typename T> // Used when x is real
T bar(T x) { return foo<T,T>(x); }
template <typename T> // Overload takes precedence when x is complex
complex<T> bar(complex<T> x) { return foo<complex<T>,T>(x); }
but that seems pretty cumbersome, especially since I need to define these for each such function I write. Is there a better way to do this?
In this example, I can do:
template <typename numeric_t>
numeric_t bar(numeric_t x) {
auto y = abs(x);
return x/y;
}
because abs() has been appropriately overloaded. And that's great! That's exactly what I'm looking for. But what if I'm not calling abs? Or if real_t is the return type?
Aucun commentaire:
Enregistrer un commentaire