Calling template function without <>; type inference
the conclusion be to avoid functions with return and more prefer void functions that return via a reference when writing templates
No, why? What do you gain? Only type inference (so less code to write). But you lose the much more logical syntax of assigning a value (and consequently more code to write). So one thing gained, another lost. I don’t see the benefit in general.
It may even help to have to specify the template type explicitly: consider the case of lexical_cast
. Not specifying the return template type would be confusing.
Overload resolution is done only based on function arguments; the return value is not used at all. If the return type cannot be determined based on the arguments, you will have to specify it explicitly.
I would not go down the path of "returning" a value through a reference parameter; that makes the calling code unclear. For example, I'd prefer this:
double x = round<double>(y);
over this:
double x;
round(x, y);
because in the latter case, it's easy to confuse input and output, and it's not at all clear that x
is being modified.
In the particular case of round
, you probably need only one or two types for TOut
anyway, so you could just leave that template argument out:
template<typename TIn>
int roundToInt(TIn v) {
return (int)(v + 0.5);
}
I find roundToInt(x)
a little clearer than round<int>(x)
because it's clear what the int
type is used for.
Let me add to what the others have said by saying you should prefer C++ casting over C-style casting.
vret = (TOut)(vin + 0.5);
versus
vret = static_cast<TOut>(vin + 0.5);
static cast will always fail if you try to convert unrelated types. This can help with debugging.