Default arguments and variadic functions - c++

Is there any way to specify a default parameter in a variadic function?(Applies to templates also)

In C++ you can replace the variadic function with one based on the Named Parameter Idiom.
See the C++ FAQ item 10.20 What is the "Named Parameter Idiom"?.
That gives you default functionality & convenient notation.
Cheers & hth.,

Why would you need both variadic and default params?
For example,
myFunc(int a=5, int b=5, int c=5);
can receive 0-3 parameters with default values, and
myFunc(...)
can reveive any number of parameters. Inside the function, you can check for missing parameters and fill in the default values as required.

First a C++ answer.
A default parameter is a parameter for which you will know that the function should and will see as provided. So you should definitively name these parameters and then may provide default arguments. This would be a "short" version of your function.
If in addition to these default arguments behind you want to have the possibility of having a va_arg argument list just overload your function with a second version that does exactly this. For that "long" version you have to provide all arguments anyhow, so there would be no sense in having default arguments, here.
Now a C answer
Probably you were not looking into such a thing, but with the va_arg macro features of C99 it is possible to define default arguments for functions in C, too. The macro syntax then is more permissive than it is for C++ in that you may also omit arguments in the middle of a function call, not only at the end. So if you would have declared your function something like
int toto(int a, ...)
and specified default arguments for positions 2 and 3, say, you could call it as
toto(4,5,,,37);
So in this sense in C it is possible to do what you asked for. I personally would certainly hesitate to do this.

No there is not way of doing that.

Related

Default arguments vs overloads, when to use which

In Kotlin there are two ways to express an optional parameter, either by specifying default argument value:
fun foo(parameter: Any, option: Boolean = false) { ... }
or by introducing an overload:
fun foo(parameter: Any) = foo(parameter, false)
fun foo(parameter: Any, option: Boolean) { ... }
Which way is preferred in which situations?
What is the difference for consumers of such function?
In Kotlin code calling other Kotlin code optional parameters tend to be the norm over using overloads. Using optional parameters should be you default behavior.
Special cases FOR using defaulted values:
As a general practice or if unsure -- use default arguments over overrides.
if you want the default value to be seen by the caller, use default values. They will show up in IDE tooltips (i.e. Intellij IDEA) and let the caller know they are being applied as part of the contract. You can see in the following screenshot that calling foo() will default some values if values are omitted for x and y:
Whereas doing the same thing with function overloads hides this useful information and just presents a much more messy:
using default values causes bytecode generation of two functions, one with all parameters specified and another that is a bridge function that can check and apply missing parameters with their defaulted values. No matter how many defaulted parameters you have, it is always only two functions. So in a total-function-count constrained environment (i.e. Android), it can be better to have just these two functions instead of a larger number of overloads that it would take to accomplish the same job.
Cases where you might not want to use default argument values:
When you want another JVM language to be able to use the defaulted values you either need to use explicit overloads or use the #JvmOverloads annotation which:
For every parameter with a default value, this will generate one additional overload, which has this parameter and all parameters to the right of it in the parameter list removed.
You have a previous version of your library and for binary API compatibility adding a default parameter might break compatibility for existing compiled code whereas adding an overload would not.
You have a previous existing function:
fun foo() = ...
and you need to retain that function signature, but you also want to add another with the same signature but additional optional parameter:
fun foo() = ...
fun foo(x: Int = 5) = ... // never can be called using default value
You will not be able to use the default value in the 2nd version (other than via reflection callBy). Instead all foo() calls without parameters still call the first version of the function. So you need to instead use distinct overloads without the default or you will confuse users of the function:
fun foo() = ...
fun foo(x: Int) = ...
You have arguments that may not make sense together, and therefore overloads allow you to group parameters into meaningful coordinated sets.
Calling methods with default values has to do another step to check which values are missing and apply the defaults and then forward the call to the real method. So in a performance constrained environment (i.e. Android, embedded, real-time, billion loop iterations on a method call) this extra check may not be desired. Although if you do not see an issue in profiling, this might be an imaginary issue, might be inlined by the JVM, and may not have any impact at all. Measure first before worrying.
Cases that don't really support either case:
In case you are reading general arguments about this from other languages...
in a C# answer for this similar question the esteemed Jon Skeet mentions that you should be careful using defaults if they could change between builds and that would be a problem. In C# the defaulting is at the call site, whereas in Kotlin for non-inlined functions it is inside of the (bridge) function being called. Therefore for Kotlin it is the same impact for changing hidden and explicit defaulting of values and this argument should not impact the decision.
also in the C# answer saying that if team members have opposing views about use of defaulted arguments then maybe don't use them. This should not be applied to Kotlin as they are a core language feature and used in the standard library since before 1.0 and there is no support for restricting their use. The opposing team members should default to using defaulted arguments unless they have a definitive case that makes them unusable. Whereas in C# it was introduced much later in the life cycle of that language and therefore had a sense of more "optional adoption"
Let's examine how functions with default argument values are compiled in Kotlin to see if there's a difference in method count. It may differ depending on the target platform, so we'll look into Kotlin for JVM first.
For the function fun foo(parameter: Any, option: Boolean = false) the following two methods are generated:
First is foo(Ljava/lang/Object;Z)V which is being called when all arguments are specified at a call site.
Second is synthetic bridge foo$default(Ljava/lang/Object;ZILjava/lang/Object;)V. It has 2 additional parameters: Int mask that specifies which parameters were actually passed and an Object parameter which currently is not used, but reserved for allowing super-calls with default arguments in the future.
That bridge is called when some arguments are omitted at a call-site. The bridge analyzes the mask, provides default values for omitted arguments and then calls the first method now specifying all arguments.
When you place #JvmOverloads annotation on a function, additional overloads are generated, one per each argument with default value. All these overloads delegate to foo$default bridge. For the foo function the following additional overload will be generated: foo(Ljava/lang/Object;)V.
Thus, from the method count point of view, in a situation when a function has only one parameter with default value, it's no matter whether you use overloads or default values, you'll get two methods. But if there's more than one optional parameter, using default values instead of overloads will result in less methods generated.
Overloads could be preferred when the implementation of a function gets simpler when parameter is omitted.
Consider the following example:
fun compare(v1: T, v2: T, ignoreCase: Boolean = false) =
if (ignoreCase)
internalCompareWithIgnoreCase(v1, v2)
else
internalCompare(v1, v2)
When it is called like compare(a, b) and ignoreCase is omitted, you actually pay twice for not using ignoreCase: first is when arguments are checked and default values are substituted instead of omitted ones and second is when you check the ignoreCase in the body of compare and branch to internalCompare based on its value.
Adding an overload will get rid of these two checks. Also a method with such simple body is more likely to be inlined by JIT compiler.
fun compare(v1: T, v2: T) = internalCompare(v1, v2)

How do to pass variable number of arguments to a function in c++ with no named parameters

I need to write a function which takes a variable number of arguements, its essentially a wrapper around a snprintf like function. I understand how to do this in general as shown in Passing variable number of arguments around.
How ever it appears that, atleast in C, we are required to pass one named parameter to the function before the variable arguments start( Why is void f(...) not allowed in C? ).
However the answers to the same questions say this is easily possible in C++. I was wondering how to achieve this, especially since the method for handling vararg functions seems to be the same as C(va_start, etc). Or are they referring to variadic templates?
So basically is it possible to write a variadic function with no named arguements, as shown below, and if so, how?
void f(...){
...
}
p.s. I would like to do this with c++03 if possible.
While C++ language allows writing functions whose parameter list consist only of ..., the language provides no means for accessing the arguments in functions declared with (...) parameter list.
Basically such functions in C++ exist for their behavior in overload resolution (... parameters match any parameter type). The body of such function will not have access to the arguments. If you see no uses for such functions, just don't use them.
Such functions are often used in non-executed context in some well-known template meta-programming techniques, in which case they don't even have to be defined - a mere declaration is sufficient.

variadic function - how to ensure parameters passed correctly

Is there any way (built-in or a code pattern) to ensure that a variadic function is passed the correct number of parameters? (This will be included as part of an API obviously, I can check my own internal code.)
I was considering requiring a UN32 Magic Number to be the last argument passed and check that for validity in the variadic function. Does anyone have any thoughts on that?
va_* macros just pop the variables from the local stack, so you have to trust the user. passing an array/size tuple could be safer, I think.
You could use the PP_NARG macro to add a count semi-automatically.
int myfunc (int count, ...);
#define MYFUNC(...) myfunc(PP_NARG(__VA_ARGS__), __VA_ARGS__)
MYFUNC(a,b,c,d);
MYFUNC(a,b,c,d,e,f,g);
gcc -E produces:
int myfunc (int count, ...);
myfunc(4, a,b,c,d);
myfunc(7, a,b,c,d,e,f,g);
There is no definitive way in C or C++ to ensure that the correct number of arguments have been passed to a variadic function. Even requiring a signature is not guaranteed to work as it may clash with the value of a valid argument. You will probably be much better off passing a vector<> as the element count retrieved is accurate.
Couldn't you use the variadic template feature of C++0x applied to a function? This would generate a vararg function that is type-safe .
See this link with it's type-safe printf implementation using a variadic templated function
http://www2.research.att.com/~bs/C++0xFAQ.html#variadic-templates
It depends on what you mean by "ensure that a variadic function is passed the correct number of parameters"...
Passing a UN32 Magic Number as last argument will allow you to determine where the list of arguments ends, so their overall number. So, by counting how many arguments you have found before UN32, you know how many arguments you have and your function should know whether is it enough. Don't know if it is ok for you to determine this at run-time (it could be too late)...
Anyway, usually variadic functions have a fixed argument list portion representing the mandatory arguments (at least one); so possibly this should be the way for you to ensure that the function gets the correct number of arguments...
No. Not possible.
Variadic breaks type-safety in a way that cannot be fixed.
If you want type-safety back, then consider breaking variadic function into several typesafe
member function of a [small] class that holds the shared state between their calls.
This is always possible, even if multiple calls might look awkward compared to single variadic
call.
Shared state is probably why you wanted variadic function in the first place.
Take iostream vs printf as example.

Function argument already initialized in function declaration C++

So here's my question in the function declaration there is an argument and it is already initialized to a certain value. What are the procedures to call this function and use that default value, or is it just a way to document code, telling other programmers what you expect them to use as a value for the parameter? Thank you.
enum File
{
XML = 0,
PDF = 1,
};
Char *SetSection(const File = XML);
If I understand your question correctly, simply calling SetSection with no parameters will do.
SetSection();
The above call gets translated (for lack of a better term) to:
SetSection(XML);
It means that the function can be called without parameters in which case the default value, XML, will be used.
In this case, File is a default argument. Calling SetSection() without arguments will set the File argument to the default value specified in the declaration.
If you call
SetSection();
It will call SetSection(XML) instead.
This is why the optional parameters have to be at the end of all parameters. If you don't provide enough parameters, it will use the default.
XML is the standard parameter.
You can call it with SetSection(); (But SetSection(XML) or SetSection(PDF) are valid, too).
What you are seeing in the declaration is a default argument value.
If you call SetSection(); it is the same as calling SetSection(XML);
You can also call SetSelection(PDF); or use any other valid parameter to override the default.
You may also be seeing the result of an incremental development which started with the function having no parameter and calls to the function scattered throughout the code. Then the alternative file type of PDF was introduced, but the prototype was changed to have a default value, which meant not having to change the existing call site.

Wrap a variable parameter function in C++

I would like to wrap the xmlrpc "call" function (which takes a variable number of parameters) with another function (also taking a variable number of parameters). I would like to simply forward the variable number of parameters I get passed in to my wrapper function to the xmlrpc "call" function.
I know how to use va_start and va_arg, but I really don't care about the values that are passed in, I simply want to forward them along to the wrapped function.
Is this possible?
the spec for the function i would like to wrap is
call(const char* url, const char* function, const char* paramSpec, void* result, ...);
my wrapper takes care of the first three parameters and the by reference result, it just needs to forward its extra parameters over to the call function
Unfortunately, there is no way to provide perfect forwarding of a function that takes a variable number of arguments via the ... syntax. This is why it is a best practice to implement all public variable argument list functions in terms of functions taking a va_list and provide both interfaces to any client code. This is why there is printf and vprintf, sprintf and vsprintf, etc. in the standard library.
If there isn't a vcall or similar taking a va_list then there is no easy way to do what you want. The only possibility is to interpret the other parameters to work out what must be in the variable argument list passed to your function based on the supplied fixed parameters, to pull all the arguments from the variable argument list into separate variables and make one of a number of possibly explicit calls to call based on the number and type of arguments extracted. It is not possible to do this with complete generality.
Yes, if you have control over the wrapped function, change from "..." to va_list. Look at vprintf as an example.
Not sure if you can wrap (...) with another (...)
This may be possible with evil hacks on some platforms. On x86, arguments are pushed onto the stack from right to left, so if you were to remove the return address from the stack, push your additional arguments, then replace it, you could (in theory) do what you want. The hard part is when you then want to do something with the return value from within the wrapper...