Passing optional parameter by reference in c++

后端 未结 10 1830
天涯浪人
天涯浪人 2020-12-02 22:39

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

相关标签:
10条回答
  • 2020-12-02 23:20

    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);
    
       // ...
    
    0 讨论(0)
  • 2020-12-02 23:23

    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.

    0 讨论(0)
  • 2020-12-02 23:26

    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);
    }
    
    0 讨论(0)
  • 2020-12-02 23:26

    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...

    0 讨论(0)
提交回复
热议问题