0

How to make optional parameters is C++?

I'm a bit lazy, I don't want to write cout <<...<<endl; everytime. If I define a macro with 1 required parameter, but 2 optional ones, how would I do that. (just for context, ^ = optional) #define P(x, ^y, ^z) std::cout << x << y << z << endl; P("hello ", "world!"); >>> outputs: hello world!

29th Jun 2020, 9:23 AM
Clueless Coder
Clueless Coder - avatar
3 Respuestas
29th Jun 2020, 9:31 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 5
Don't use a macro, use proper variadic templates: template<typename First> void print( First&& f ) { std::cout << std::forward<First>( f ); } template<typename First, typename... Args> void print( First&& f, Args&&... args ) { std::cout << std::forward<First>( f ) << ' '; print( std::forward<Args>( args )... ); } Should work, call it like print( 1, 'w', 2.6, "Hello" ); ( as many as you want ) But if you really want to use a macro, it also supports variable parameters like P( ... ) then you you refer to it by using __VA_ARGS__ in the macro. But a macro should be avoided if you can.
29th Jun 2020, 9:53 AM
Dennis
Dennis - avatar
+ 2
Dennis Thanks. I'll look into it, at the moment I really don't get what you put.
29th Jun 2020, 10:29 AM
Clueless Coder
Clueless Coder - avatar