是否有可能编写一个函数模板来返回参数的数量是否能被N整除?
Is it possible to write a function template which returns whether the number of arguments is divisible by 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;
}
或者,您可以返回一个对元编程更友好的类型:
template<int N, typename... Ts>
constexpr integral_constant<bool, sizeof...(Ts) % N == 0>
number_of_args_divisible_by(Ts&&...)
{
return {};
}
虽然krzaq的解决方案非常好,但我认为实现sizeof...
背后的"魔法"可以作为一个有趣的学习练习。
它使用了一种模板元编程中非常常见的技术——一个覆盖基本情况的非模板函数和一个通过一步减少问题的模板函数:
// Base case
int count_args() {
return 0;
}
// Reduction
template<typename T, typename... Vs>
int count_args(T _, Vs... vs) {
return 1 + count_args(vs...);
}
有了这个功能,您可以使用krzaq的答案中的方法实现可除性检查器:
template<int N,typename... Vs>
bool is_arg_divisible(Vs... vs) {
return count_args(vs...) % N == 0;
}
演示。
相关文章:
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 是否可以对零模板参数进行模板专门化
- 函数作为模板参数,是否对返回类型强制约束
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 函数是否可以访问传递给main()的参数
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 如何检查给定的参数是否为 cv::noArray()?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 如果返回 -1,时间() 的参数是否被修改?
- 用于检查值是否为其任何参数的帮助程序函数
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 模板化检查是否存在带有参数列表的类成员函数?
- 我如何知道作为参数的size_t在函数中是否有效?
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 是否可以在运行时强制转换模板参数?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 编译器是否强制根据模板参数计算表达式?
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?