How can I cleanly specify which arguments I am passing and which remain default?

前端 未结 4 1842
醉酒成梦
醉酒成梦 2020-12-06 18:23

Asked because of this: Default argument in c++

Say I have a function such as this: void f(int p1=1, int p2=2, int p3=3, int p4=4);

And

4条回答
  •  情书的邮戳
    2020-12-06 19:08

    Have a look at the Boost.Parameter library.

    It implements named paramaters in C++. Example:

    #include 
    #include 
    #include 
    
    //Define
    BOOST_PARAMETER_NAME(p1)    
    BOOST_PARAMETER_NAME(p2)
    BOOST_PARAMETER_NAME(p3)
    BOOST_PARAMETER_NAME(p4)
    
    BOOST_PARAMETER_FUNCTION(
                             (void),
                             f,
                             tag,
                             (optional            
                              (p1, *, 1)
                              (p2, *, 2)
                              (p3, *, 3)
                              (p4, *, 4)))
    {
        std::cout << "p1: " << p1 
                << ", p2: " << p2
                << ", p3: " << p3
                << ", p4: " << p4 << "\n";
    }
    //Use
    int main()
    {
        //Prints "p1: 1, p2: 5, p3: 3, p4: 4"
        f(_p2=5);
    }
    

提交回复
热议问题