0

Variable number of arguments in C++? In this post you will find a way to write variable arguments for template,

template <typename T>
void func(T t) 
{
    std::cout << t << std::endl ;
}

template<typename T, typename... Args>
void func(T t, Args... args) // recursive variadic function
{
    std::cout << t <<std::endl ;

    func(args...) ;
}

But in my case, type name is certain,

template <int... args>
constexpr auto sum(int a, ...) {
    return a + sum(args...);
}
constexpr auto sum(int a, int b) {
    return a + b;
}
void test() {
    cout << sum(1, 2) << endl;
    cout << sum(1, 2, 3) << endl;
    cout << sum(1, 2, 3, 4) << endl;
}

It's not working with sum(args...), prompts error

Error   C2660   '__syntaxTest::sum': function does not take 0 arguments ForTest 

Do you have any suggestion about this?

Zhang
  • 3,030
  • 2
  • 14
  • 31
  • There's no way the compiler could deduce `` from `sum(1, 2)` (or other invocations). Moreover `sum(int a, ...)` does not to what you think it does – Sergey Kolesnik Aug 25 '22 at 04:03
  • See dupe: [Can I create a function which takes any number of arguments of the same type?](https://stackoverflow.com/questions/70014236/can-i-create-a-function-which-takes-any-number-of-arguments-of-the-same-type) – Jason Aug 25 '22 at 04:08
  • https://godbolt.org/z/c5q39qvea here is an example that shows what is wrong with your code. `(int a, ...)` is a *C variadic*, not a template variadic. The link shows you the difference. – Sergey Kolesnik Aug 25 '22 at 04:20

0 Answers0