Passing optional parameter by reference in c++

后端 未结 10 1829
天涯浪人
天涯浪人 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:02

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

    It is much easier to use a pointer type and setting it to NULL than setting default/optional value for a reference parameter.

    0 讨论(0)
  • 2020-12-02 23:02
    void foo(double &bar,
             double &foobar = const_cast<double &>(static_cast<const double &>(0.0)))
    {
       bar = 100;
       foobar = 150;
    }
    
    0 讨论(0)
  • 2020-12-02 23:03

    You can do this crazy way:

    void foo(double &bar, double &foobar = (*(new double())))
    

    P.S. - I know its not pleasant but its the way. Also be sure not to leave memory leaks! :))

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

    Here is another crazy way that does not result in memory leaks, which you should never use in real life, but seems to be standard compliant at first glance and compiles with Visual C++ 2008 & g++ 3.4.4 under Cygwin:

    void foo(double &bar, double &foobar = (*((double*)0)))
    {
       bar = 100;
       double* pfoobar = &foobar;
       if (pfoobar != 0)
           foobar = 150;
    }
    

    To reiterate: DON'T DO THIS! THERE ARE BETTER OPTIONS! OVERLOADING CAN BE YOUR FRIEND! But yeah, you can do it if you're foolish and careful. :)

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

    The default argument of a (mutable) reference must be an l-value. The best I can think of, without overloading, is

    static double _dummy_foobar;
    void foo(double &bar, double &foobar = _dummy_foobar)
    
    0 讨论(0)
提交回复
热议问题