2

I can write the following to define a function taking any number of arguments:

template <typename... Arguments>
void f(Arguments... sums) {
    // Do something.
}

and then call it like

f(1, 2, 3, 4);

But how do I restrict all arguments to e.g. int?

m.s.
  • 16,063
  • 7
  • 53
  • 88
Petter
  • 37,121
  • 7
  • 47
  • 62

2 Answers2

3

Employing all_true from this SO answer you could use the following:

#include <type_traits>

template <bool...> struct bool_pack;

template <bool... v>
using all_true = std::is_same<bool_pack<true, v...>, bool_pack<v..., true>>;

template<typename... Args,
         typename = std::enable_if_t<all_true<std::is_same<int, Args>{}...>{}>>
void f(Args... sums)
{
    // Do something.
}

int main()
{
    f(1, 2, 3, 4);
    f(1.1, 2, 3, 4); // compile error
}

live example

Community
  • 1
  • 1
m.s.
  • 16,063
  • 7
  • 53
  • 88
  • Excellent! This works in Clang 3.6, but not in VS 2015, unfortunately. – Petter Jan 17 '16 at 20:16
  • 1
    @Petter : For VC++ 2015, use `enable_if_t` on the return type instead of in the template parameter list and change `std::is_same<>{}` to `std::is_same<>::value`. – ildjarn Jan 17 '16 at 21:51
1

You can use std::initializer_list<int> argument for your function. But unfortunately in this case need to specify extra curly braces around arguments.

f({1, 2, 3, 4});
αλεχολυτ
  • 4,792
  • 1
  • 35
  • 71