mwhittaker - 10 months ago 38

C++ Question

I've been learning about variadic templates, and with the help of this excellent blog post, I've managed to write a function template

`even_number_of_args`

`#include <iostream>`

bool even_number_of_args() {

return true;

}

template <typename T>

bool even_number_of_args(T _) {

return false;

}

template<typename T, typename U, typename... Vs>

bool even_number_of_args(T _, U __, Vs... vs) {

return even_number_of_args(vs...);

}

int main() {

std::cout << even_number_of_args() << std::endl; // true

std::cout << even_number_of_args(1) << std::endl; // false

std::cout << even_number_of_args(1, "two") << std::endl; // true

std::cout << even_number_of_args(1, "two", 3.0) << std::endl; // false

std::cout << even_number_of_args(1, "two", 3.0, '4') << std::endl; // true

}

I was wondering if it was possible to write a function template that takes, as a template argument, a number

`N`

`N`

`number_of_args_divisible_by_N<1>(1, "two", 3.0, '4'); // true`

number_of_args_divisible_by_N<2>(1, "two", 3.0, '4'); // true

number_of_args_divisible_by_N<3>(1, "two", 3.0, '4'); // false

number_of_args_divisible_by_N<4>(1, "two", 3.0, '4'); // true

Answer Source

Yes¹, it's as simple as

```
template<int N, typename... Ts>
constexpr bool number_of_args_divisible_by(Ts&&...)
{
return sizeof...(Ts) % N == 0;
}
```

Alternatively, you can return a more metaprogramming-friendly type:

```
template<int N, typename... Ts>
constexpr integral_constant<bool, sizeof...(Ts) % N == 0>
number_of_args_divisible_by(Ts&&...)
{
return {};
}
```

¹ it's actually a function template, but so is `even_number_of_args`

in the question. Refer to Kaz's answer if you need an actual function (the answer's *no*, though).