C++11 variable number of arguments, same specific type

Skeen picture Skeen · Aug 2, 2013 · Viewed 30.3k times · Source

Question is simple, how would I implement a function taking a variable number of arguments (alike the variadic template), however where all arguments have the same type, say int.

I was thinking about something alike this;

void func(int... Arguments)

Alternatively wont a recursive static assert on the types work?

Answer

hmjd picture hmjd · Aug 2, 2013

A possible solution is to make the parameter type a container that can be initialized by a brace initializer list, such as std::initializer_list<int> or std::vector<int>. For example:

#include <iostream>
#include <initializer_list>

void func(std::initializer_list<int> a_args)
{
    for (auto i: a_args) std::cout << i << '\n';
}

int main()
{
    func({4, 7});
    func({4, 7, 12, 14});
}