[英]Is it possible to define the amount of arguments in a function with variable number of arguments by a global variable
I want to define a function with variable amount of arguments, where this amount should be fixed by a global variable, say N
, and I thought of using a va_list to achieve that. 我想用一个可变数量的参数定义一个函数,该数量应该由一个全局变量
N
来固定,我想到了使用va_list来实现。 Is it possible to declare that function without any reference to the number of arguments, thus without having to enter N
as the first variable when calling it, but only the rest of them? 是否可以在不引用参数数量的情况下声明该函数,从而在调用该函数时不必输入
N
作为第一个变量,而只需输入其余变量? If not, is there a way other than using a va_list to do this? 如果不是,除了使用va_list之外,还有其他方法吗?
Now I just declared it according to the standard way and in its definition I assign the value of N
to the first argument of that function (so that, no matter which integer one uses as first argument, it always has the desired value). 现在,我只是按照标准方法对其进行了声明,并在其定义中将
N
的值分配给该函数的第一个参数(因此,无论哪个整数用作第一个参数,它始终具有所需的值)。 Is there a more elegant way? 有没有更优雅的方式?
Not sure to understand what do you want. 不知道您想要什么。
But if you can use at least C++11, and if you accept to use variadic templates for variable amounts of arguments, I propose the use of SFINAE to impose that the variable number of arguments is exaclty N
但是,如果您至少可以使用C ++ 11,并且如果您接受对可变数量的参数使用可变参数模板,那么我建议使用SFINAE强制将可变数量的参数指定为
N
The following is a full working example 以下是完整的工作示例
#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's is the correct answer to the original question: how to have a variable number of arguments and constrain the number of arguments. max66是对原始问题的正确答案:如何拥有可变数量的参数并限制参数数量。
However, the number of function arguments sits squarely in the world of compile-time. 但是,函数参数的数量在编译时至关重要。 What you probably want is a single argument of type
std::vector
. 你可能想要的是类型的一个参数
std::vector
。 std::vector
contains a variable number of values of the same type. std::vector
包含可变数量的相同类型的值。 If you want to set at runtime what that length should always be, then you probably want to check the length and throw an exception if it's wrong. 如果要在运行时设置该长度应始终为多少,则可能需要检查该长度并在错误的情况下引发异常。
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;
}
And then you can call that with 然后你可以用
const int just_ten = sum({1, 2, 3, 4});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.