1

For example if I have

int MyFunction(int,...);//no. of parameters is unknown

And in main()

MyFunction(1,2,3,4);

The returned value should be 4.I've tried stdarg.h but to use that you have to know the number of parameters, so it doesn't hold up for me.Thanks!

asmmo
  • 6,922
  • 1
  • 11
  • 25
  • First solution that comes in mind would be creating a va_list https://en.cppreference.com/w/cpp/utility/variadic and applying one of the answers provided here https://stackoverflow.com/questions/2598132/length-of-va-list-when-using-variable-list-arguments – EagleOne May 09 '20 at 09:55

2 Answers2

4

Just return the number of arguments in a parameter pack.

template<typename ...Args>
unsigned MyFunction(Args... args) {
    return sizeof...(args);
}

int main() {
    return MyFunction(1,2,3);
}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

You may learn and use variadic templates, as follows

#include <iostream>

template <typename ... Types>
size_t func(Types ... args){

    return sizeof...(args);
}

int main()
{
    std::cout << func(1, 2, 3, 4);
}
asmmo
  • 6,922
  • 1
  • 11
  • 25