Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing optional parameter by reference in c++

I'm having a problem with optional function parameter in C++

What I'm trying to do is to write function with optional parameter which is passed by reference, so that I can use it in two ways (1) and (2), but on (2) I don't really care what is the value of mFoobar.

I've tried such a code:

void foo(double &bar, double &foobar = NULL) {    bar = 100;    foobar = 150; }  int main() {   double mBar(0),mFoobar(0);    foo(mBar,mFoobar);              // (1)   cout << mBar << mFoobar;    mBar = 0;   mFoobar = 0;    foo(mBar);                     // (2)   cout << mBar << mFoobar;    return 0; } 

but it crashes at

void foo(double &bar, double &foobar = NULL) 

with message :

error: default argument for 'double& foobar' has type 'int' 

Is it possible to solve it without function overloading?

like image 736
Moomin Avatar asked May 12 '10 05:05

Moomin


People also ask

Can we pass parameters by reference in C?

Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.

How do you pass an optional parameter?

By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.

Can you have optional parameters in C?

C does not support optional parameters.

What is passing parameters by reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.


1 Answers

Don't use references for optional parameters. There is no concept of reference NULL: a reference is always an alias to a particular object.

Perhaps look at boost::optional or std::experimental::optional. boost::optional is even specialized for reference types!

void foo(double &bar, optional<double &> foobar = optional<double &>()) 
like image 150
Potatoswatter Avatar answered Oct 08 '22 16:10

Potatoswatter