强制使用默认参数

Force the use of a default parameter

本文关键字:默认 参数      更新时间:2023-10-16

"简单"问题,在调用需要默认参数的函数时,是否可以显式使用默认参数?类似于:

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参数库。

小示例:

#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);
}

实例

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