Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic function template base case: without parameters or with one?

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:

  1. Base case is sum():

    auto sum() 
    { 
        return 0; 
    }
    
  2. 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?

like image 949
MeyCey Avatar asked Sep 27 '22 07:09

MeyCey


1 Answers

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

like image 130
Jarod42 Avatar answered Oct 17 '22 04:10

Jarod42