I have seen a lot of links introducing the variadic templates. But I have never seen any compilable example that demonstrates this approach.
Could someone provide me
One of the simplest possible examples is the following implementation of max
which isn't even templated on types.
int maximum(int n)
{
return n;
}
template
int maximum(int n, Args... args)
{
return max(n, maximum(args...));
}
Only slightly more complex is the canonical printf
implementation:
void printf(const char *s)
{
while (*s)
{
if (*s == '%' && *(++s) != '%')
throw "invalid format string: missing arguments";
std::cout << *s++;
}
}
template
void printf(const char* s, T value, Args... args)
{
while (*s)
{
if (*s == '%' && *(++s) != '%')
{
std::cout << value;
printf(s, args...); // call even when *s == 0 to detect extra arguments
return;
}
std::cout << *s++;
}
throw "extra arguments provided to printf";
}