强制使用默认参数

时间:2015-02-18 13:54:08

标签: c++ function default-parameters

“简单”问题,是否可以在调用期望的函数时显式使用默认参数?类似的东西:

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

谢谢

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

不,目前在C ++中是不可能的。

相关问题