![](/img/trans.png)
[英]Is there an easier way to do a macro to define a function with variable amount of arguments?
[英]Is it possible to define the amount of arguments in a function with variable number of arguments by a global variable
我想用一个可变数量的参数定义一个函数,该数量应该由一个全局变量N
来固定,我想到了使用va_list来实现。 是否可以在不引用参数数量的情况下声明该函数,从而在调用该函数时不必输入N
作为第一个变量,而只需输入其余变量? 如果不是,除了使用va_list之外,还有其他方法吗?
现在,我只是按照标准方法对其进行了声明,并在其定义中将N
的值分配给该函数的第一个参数(因此,无论哪个整数用作第一个参数,它始终具有所需的值)。 有没有更优雅的方式?
不知道您想要什么。
但是,如果您至少可以使用C ++ 11,并且如果您接受对可变数量的参数使用可变参数模板,那么我建议使用SFINAE强制将可变数量的参数指定为N
以下是完整的工作示例
#include <type_traits>
static constexpr std::size_t N = 3U;
template <typename ... Args>
typename std::enable_if<N == sizeof...(Args), int>::type foo (Args ... as)
{ return 0; }
int main ()
{
//foo(0, 1); // compilation error
foo(0, 1, 2); // compile
//foo(0, 1, 2, 3); // compilation error
}
max66是对原始问题的正确答案:如何拥有可变数量的参数并限制参数数量。
但是,函数参数的数量在编译时至关重要。 你可能想要的是类型的一个参数std::vector
。 std::vector
包含可变数量的相同类型的值。 如果要在运行时设置该长度应始终为多少,则可能需要检查该长度并在错误的情况下引发异常。
size_t N__ = 4;
int sum(const std::vector<int>& vec) {
if (vec.size() != N__) { throw std::length_error("error message"); }
int out = 0;
for (int i_ : vec) { out += i_; }
return out;
}
然后你可以用
const int just_ten = sum({1, 2, 3, 4});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.