Specifying default parameter when calling C++ function

前端 未结 5 492
慢半拍i
慢半拍i 2020-12-09 18:23

Suppose I have code like this:

void f(int a = 0, int b = 0, int c = 0)
{
    //...Some Code...
}

As you can evidently see above with my cod

5条回答
  •  独厮守ぢ
    2020-12-09 18:43

    Not exactly what you ask, but you can use std::bind() to fix a value for a parameter.

    Somethink like

    #include 
    
    void f(int a = 0, int b = 0, int c = 0)
    {
        //...Some Code...
    }
    
    int main()
    {
       //Here are 4 ways of calling the above function:
       int a = 2;
       int b = 3;
       int c = -1;
    
       f(a, b, c);
       f(a, b);
       f(a); 
       f();
       //note the above parameters could be changed for the other variables
       //as well.
    
       using namespace std::placeholders;  // for _1, _2
    
       auto f1 = std::bind(f, _1, 0, _2);
    
       f1(a, c); // call f(a, 0, c);
    
       return 0;
    }
    

    With std::bind() you can fix values different from default parameters values or values for parameters without default values.

    Take just in count that std::bind() is available only from C++11.

    p.s.: sorry for my bad English.

提交回复
热议问题