是否有可能写一个函数模板,返回参数的数量是否可以被N整除?

我一直在学习可变参数模板,在这篇出色的博客文章的帮助下,我设法编写了一个函数模板even_number_of_args ,它返回它收到的参数个数是否可​​以被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 } 

我想知道是否有可能编写一个函数模板,它将模板参数作为一个数字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 

是的,这很简单

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

或者,您可以返回一个更易于元编程的types:

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

虽然krzaq的解决scheme是相当不错的,但我认为,实施sizeof...背后的“魔术”可以成为一个有趣的学习练习。

它使用了一种模板元编程非常普遍的技术 – 覆盖基本情况的非模板函数,以及通过一个步骤减less问题的模板函数:

 // Base case int count_args() { return 0; } // Reduction template<typename T, typename... Vs> int count_args(T _, Vs... vs) { return 1 + count_args(vs...); } 

有了这个function,您可以使用krzaq的答案来实现可分性检查器:

 template<int N,typename... Vs> bool is_arg_divisible(Vs... vs) { return count_args(vs...) % N == 0; } 

演示。