This question already has answers here:
Skip some arguments in a C++ function?

(4个答案)


5年前关闭。




“简单”问题,在调用需要一个函数时是否可以显式使用默认参数?就像是 :
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

谢谢

最佳答案

不适用于标准C++,但您可以查看boost parameter library.

小例子:

#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

关于c++ - 强制使用默认参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28585362/

10-11 21:04