Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether function parameter was automatically set to default value or was set explicitly in C++?

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);
like image 707
johngreen Avatar asked Sep 15 '14 07:09

johngreen


People also ask

How do you define the default value of a function parameter?

ECMAScript 2015 allows default parameter values in the function declaration: function myFunction (x, y = 2) { // function code. } Try it Yourself »

What are the parameters that are default values?

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.

What is default parameter can we use default parameter for first parameter in function?

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.

Can you assign the default values to a function parameters True or false?

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.


1 Answers

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.

like image 157
John Zwinck Avatar answered Nov 15 '22 00:11

John Zwinck