I saw a blog post which used non-type variadic templates (currently not supported by gcc, only by clang).
template <class T, size_t... Dimensions>
struct MultiDimArray { /* ... */ };
The example in the post compiles fine but I failed to get it to work with function templates.
Can anyone help figuring out the correct syntax (if such exists)?
int max(int n) { return n; } // end condition
template <int... N> // replacing int... with typename... works
int max(int n, N... rest) // !! error: unknown type name 'N'
{
int tmp = max(rest...);
return n < tmp? tmp : n;
}
#include <iostream>
int main()
{
std::cout << max(3, 1, 4, 2, 5, 0) << std::endl;
}
Here are two ways of defining a variadic function template only accepting
int
parameters. The first one generates a hard-error when instantiated, the second uses SFINAE:As you can see, non-type template parameters aren't used here.
Here's how you could achieve variadic args in your
max
example such that it can take any number of arithmetic arguments:This is good because it can take any numeric type and will return the maximum number by its original type rather than just
int
, too.You are simply confusing type names and non-type names. What you want simply doesn’t work.
You can probably use variadic non-type templates in functions, but not as (non-template) arguments:
… although I haven’t tested this and I’m not sure how this should work given that you need to have a partial specialisation as the base case. You could solve this by dispatching to a partially specialised struct:
This will work.
Luc Danton's solution doesn't behave correctly with parameters which are not of type
int
, but can be implicitly converted to anint
. Here's one which does:Here,
max
forwards all arguments unchanged tomax_checked
, which takes the same number of arguments of typeint
(provided by performing a pack-expansion on thefirst_type
template). Thedecltype(...)
return type is used to apply SFINAE if any argument can't be converted toint
.This will print out all elements, get max could be implemented similarly