Variable number of arguments in C++?

后端 未结 17 1770
-上瘾入骨i
-上瘾入骨i 2020-11-21 23:13

How can I write a function that accepts a variable number of arguments? Is this possible, how?

17条回答
  •  梦如初夏
    2020-11-21 23:33

    // spawn: allocate and initialize (a simple function)
    template
    T * spawn(size_t n, ...){
      T * arr = new T[n];
      va_list ap;
      va_start(ap, n);
      for (size_t i = 0; i < n; i++)
        T[i] = va_arg(ap,T);
      return arr;
    }
    
    

    User writes:

    auto arr = spawn (3, 0.1,0.2,0.3);
    

    Semantically, this looks and feels exactly like an n-argument function. Under the hood, you might unpack it one way or the other.

提交回复
热议问题