I'm quite sure this is not possible, but if someway exists (maybe through compiler-provided macros), it would be very useful for me, so I am posting it here. Suppose I have a function:
void func( int param1, bool param2=false){ ... }
param2
has been given a default value here. Is there any mechanism to determine if param2
was explicitly set to its default value false
or was it passed automatically? In other words, from within function func
, is it possible to distinguish between the following two calls? I am using Microsoft Visual C++ Compiler.
func(1, false);
and
func(1);
ECMAScript 2015 allows default parameter values in the function declaration: function myFunction (x, y = 2) { // function code. } Try it Yourself »
A parameter with a default value, is often known as an "optional parameter". From the example above, country is an optional parameter and "Norway" is the default value.
When no value is passed in the function definition, a default value is being set for the function definition, known as the default parameter. It allows the named parameters to get initialized with a default value when either undefined or no value is passed.
Yes, it is correct that you can assign a default value to the parameter before calling the function, which results in you not needing to pass an argument when calling the function. The default parameter is however always overridden if you pass a value to the function.
You can't distinguish the way you're asking, but you can do this:
void func(int param1, boost::optional<bool> param2=boost::none);
Then you can check if param2 is none or not (it has its own operator bool). If it's set, it means it was passed in. Call sites will look the same as before, because an optional can be implicitly constructed from its value type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With