Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Macro to count the number of arguments
Parent
Macro to count the number of arguments
Let's say we have a function
void f(int argc, ...);
where argc is the number of variadic arguments.
Can we write a macro of the form
#define F(...) f(CNT(__VA_ARGS__), __VA_ARGS__)
which passes the right value in argc?
How can that CNT() be implemented?
Post
If you are on C++11 (or newer), it should be possible to use variadic templates to write a simple (compile-time) function to count the number of arguments:
template<typename... Ts>
constexpr int countArgs(const Ts&... args) {
return sizeof...(args);
}
With this function, we can go ahead and write the desired macro as follows:
#define F(...) f(countArgs(__VA_ARGS__), __VA_ARGS__)
This should work no matter what the types of the variadic arguments are.

1 comment thread