Search code examples
c++functiondefault-parameters

Force the use of a default parameter


"Simple" question, is it possible to explicitly use a default parameter when calling a function which expects one ? Something like :

void function(int x, int y = 2, int z = 3)
{
      // prints x, y and z
}

function(10, default, 13); // won't compile of course
// would return x = 10, y = 2 and z = 3

Thank you


Solution

  • Not with standard C++, but you can look at for example boost parameter library.

    Small example:

    #include <iostream>
    #include <boost/parameter.hpp>
    #include <boost/parameter/preprocessor.hpp>
    
    BOOST_PARAMETER_NAME(x)
    BOOST_PARAMETER_NAME(y)
    BOOST_PARAMETER_NAME(z)
    
    namespace tag { struct x; }
    
    BOOST_PARAMETER_FUNCTION(
          (void),
          function,
          tag,
          (required (x, (int)))
          (optional
           (y, (int), 2)
           (z, (int), 3)
          )
    )
    {
       std::cout << "Called with x = " << x << " y = "
       << y << " z = " << z << std::endl;
    }
    
    int main()
    {
       function(1, _z = 5);
       function(1, _y = 8);
    }
    

    live example