towi
towi

Reputation: 22277

Can I define a variadic template function on a single type?

Can I define a variadic template function not with a changing type, but just for a single one? If my goal is to define a function that only adds a variadic number of int, but not float, or anything else, can I do that with a template<int....> syntax somehow?

The multi-type sample I can put together easily:

int add() { return 0; }

template<typename T, typename... TS>
T add(T n, TS... m)
  { return n+add(m...); }

But how do I use int only in this? It obviously can not follow the pattern to put <int> in the template-argument-list, because I want a function that takes arguments between the (...) and not between the <...> like this:

template<int n>
int constant() { return n; }

constant<4>();  // using the int-template function

It is obvious to me that the following will not work, therefore. But as a starting point...

template<int, int...>
int add(int n, int... m)    // error, of course.
  { return n+add(m...); }

How can I define add for add(1), add(1,2), add(1,2,3) etc. but only for int-Arguments. It should not generate a float-function for add(1.0) (It may be that the call will work, but then only because 1.0 is converted to an int).

Note: I do not mean anything that would just constrain the type T or TS down with enable_if or such. I just think there might be a syntax for this kind of variadic templates that I miss here.

Upvotes: 2

Views: 499

Answers (2)

aaronman
aaronman

Reputation: 18750

For this purpose you should really just use std::initializer_list, which is very similar to a variadic function for only one type.

int add(std::initializer_list<int> list) {
    int sum = 0;
    for (auto i : list) sum += i;
    return sum;
}  

Now you can call it like this int i = add({1,2,3,4,5,6});

If you really want to you can easily put a static assert in that will do this for you.

int add() { return 0; }

template<typename T, typename... TS>
T add(T n, TS... m)
{
   static_assert(std::is_same<T,int>::value,"bad type"); 
   return n+add(m...); 
}  

But IMO this totally defeats the purpose of variadic templates, and will make the program harder to read and write.

Upvotes: 5

Constructor
Constructor

Reputation: 7473

int add() { return 0; }

template<typename... TS>
int add(int n, TS... m)
{
    return n + add(m...); 
}

What is wrong with such code?

Upvotes: 3

Related Questions