简体   繁体   中英

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. 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? If not, is there a way other than using a va_list to do this?

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). 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

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.

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 contains a variable number of values of the same type. 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});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM