mwhittaker - 11 months ago 44

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

`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 that takes, as a template argument, a number

`N`

`N`

`std::cout << number_of_args_divisible_by_N<1>(1, "two", 3.0, '4') // true`

std::cout << number_of_args_divisible_by_N<2>(1, "two", 3.0, '4') // true

std::cout << number_of_args_divisible_by_N<3>(1, "two", 3.0, '4') // false

std::cout << 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;
}
```