Is there any way to specify a default parameter in a variadic function?(Applies to templates also)
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
No there is not way of doing that.
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 likeand specified default arguments for positions 2 and 3, say, you could call it as
So in this sense in C it is possible to do what you asked for. I personally would certainly hesitate to do this.
Why would you need both variadic and default params?
For example,
can receive 0-3 parameters with default values, and
can reveive any number of parameters. Inside the function, you can check for missing parameters and fill in the default values as required.
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.,