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!
3 odpowiedzi
+ 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.
+ 2
Dennis Thanks. I'll look into it, at the moment I really don't get what you put.