mwhittaker mwhittaker - 2 months ago 9
C++ Question

Is it possible to write a C++ function which returns whether the number of arguments is divisible by N?

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
which returns whether the number of arguments it receives is divisible by 2.

#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
and returns whether the number of arguments it receives is a multiple of
N
. For example, the function may look something like this:

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

Yes, it's as simple as

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