简体   繁体   中英

Default reference argument in C++

I have class mizer :

class mizer {
  ...
  public:
    ...
    void getDeviation( vector<double>&, vector<int>& )
...
};

with realization:

void mizer::getDeviation( vector<double>& best_mass, vector<int>& best_comb ){
   ...
}

But sometimes I do not want to provide the second argument best_comb . So I want to set default or something:

void mizer::getDeviation( ..., vector<int>& best_comb = default )

I tried:

static vector<int> def();
...
void mizer::getDeviation( ..., vector<int>& best_comb = def )

But it is not working:

/minimizer/mizer.C:69:69: error: 
non-const lvalue reference to   type 'vector<int>'  cannot bind to a value of unrelated type 'vector<int> ()'double mizer::getDeviation( vector<double>&  best_mass, vector<int>& best_comb=def ){

How to set default vector reference variable?

static vector<int> def(); declares a static function def that returns a vector<int> . use static vector<int> def{}; or static vector<int> def; instead

How about function overloading ?

You could make an overloaded function taking only one argument, and then use an empty dummy vector to call the two-argument function.

You can use a method overload, like @Someprogrammerdude suggested:

class mizer {
  ...
  public:
    ...
    void getDeviation( vector<double>& );
    void getDeviation( vector<double>&, vector<int>& );
    ...
};

void mizer::getDeviation( vector<double>& best_mass )
{
   vector<int> ignored; 
   getDeviation( best_mass, ignored );
}

void mizer::getDeviation( vector<double>& best_mass, vector<int>& best_comb )
{
   ...
}

mizer m;
vector<double> mass;
m.getDeviation( mass );

mizer m;
vector<double> mass;
vector<int> comb;
m.getDeviation( mass, comb );

But that is still going to allocate memory for the content of best_comb even if the caller does not want it.

Alternatively, you can make the optional parameter be a pointer instead of a reference:

class mizer {
  ...
  public:
    ...
    void getDeviation( vector<double>&, vector<int>* = nullptr );
    ...
};

void mizer::getDeviation( vector<double>& best_mass, vector<int>* best_comb )
{
   ...
   if (best_comb) best_comb->push_back(...);
   ...
}

mizer m;
vector<double> mass;
m.getDeviation( mass );

mizer m;
vector<double> mass;
vector<int> comb;
m.getDeviation( mass, &comb );

Now no memory is allocated for the content of best_comb unless the caller wants it.

Your function def() might return always same value.

So, I think you need to use "#define" as default & reference vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM