T
T
Tash1moto2017-01-16 17:11:10
Programming
Tash1moto, 2017-01-16 17:11:10

How to find out the number of arguments passed in C++?

After python, js, for interest I look
at C ++ How can I find out the number of arguments in C ++?
For example, in python3 you can do this

f = lambda *args: print(len(args))
f(1,2,3) # выведет 3

I looked at the option with the cstdarg library, but it seems to me that this is some kind of bicycle and it is clearly necessary to specify the number of arguments as the first argument :).
So how do you know the number of arguments to pass in C++?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nexeon, 2017-01-16
@Tash1moto

Quick and easy. We count using variable patterns and the operatorsizeof

template <typename ... Args> int ArgsCount(Args ... args) {
    return sizeof...(args);
}

std::cout << ArgsCount(1, "hello", 2.f); // Вывод: 3

1
15432, 2017-01-16
@15432

C++ functions mostly have a fixed number of parameters, so there is no problem with determining the number of parameters - this is known at compile time.
Functions with a variable number of parameters (for example, printf(char* format, ...) ) have their own mechanism for determining the number of parameters, which you yourself must code at your discretion. You can submit the total number of arguments as the first argument, as you suggest.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question