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 th
Another way to do this is to use pointers instead of references. This provides the semantics that you want without overloading. (Personally, I'd probably go with overloading.)
void foo(double* bar, double* foobar = 0)
{
if (bar) *bar = 100;
if (foobar) *foobar = 150;
}
// ...
foo(&mBar, &mFoobar);
// ...
foo(&mBar);
// ...
This is how I solved this question:
My original function didn't have a returned error string: bool MyClass::validateXML(const QString& fileName, const QUri& schemaUri);
I wanted to add the results of the validation in an error string so I implemented: bool MyClass::validateXML(const QString& fileName, const QUri& schemaUri, QString& errorString = *(std::make_unique().get()));
This way, you can reference the errorString in validateXML without checking if it's valid, and no memory leaks.
Why can't you use function overloading? Surely it's the easiest solution to your problem?
void foo(double &bar, double &foobar)
{
bar = 100;
foobar = 150;
}
void foo(double &bar)
{
double foobar = 0.0;
foo(bar, foobar);
}
Speaking in terms of Object Oriented paradigm: If given class has and "Default", this Default must declared accordingly, and then may be used as an "Default Parameter" Ex:
class Pagination {
private:
int currentPage;
public:
//...
Pagination() {
currentPage = 1;
//...
}
// your Default Pagination (Must be initialized before thread concurrency)
static Pagination& Default() {
static Pagination p;
return p;
}
};
On your Method ...
//...
std::vector<User>
findByFilter(User& audit, Pagination& p = Pagination::Default() ) {
// ...
Edited: This solution is quite suitable since in this case it is an "global default" Pagination and a single "reference" value. You will also have the power to change default values such as navigation/display preferences and etc.
Edit2: spelling and fixing...