I would like to know which one of these (if any) options would be preferred.
For example I'm implementing a sum function taking arbitrary number of arguments. The main template is then
template <typename T, typename... Ts>
auto sum(T t, Ts... ts)
{
return t + sum(ts...);
}
For the base case I can see at least two options:
Base case is sum():
auto sum()
{
return 0;
}
Base case is sum( T ):
template <typename T>
auto sum(T t)
{
return t;
}
Both of those seem to work in the same way in this case, but which one would be generally preferred?
The second case is more generic than option 1 which introduce int
.
ie: with your second option, you could sum
some matrix class, whereas the first one disallows that. (You should take argument by const reference to be efficient for matrix case though).
By introducing int
, you also have different return type for some case as
auto res = sum('*');
which result in int
type for option 1 and in char
type for option 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With