强制使用默认参数
Force the use of a default parameter
"简单"问题,在调用需要默认参数的函数时,是否可以显式使用默认参数?类似于:
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++中是不可能的。
相关文章:
- 如何使用默认参数等选择模板专业化
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 何时提供默认参数作为模板参数
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 如何修复带有 clang 的参数'args'缺少默认参数的问题?
- 函数不接受 X 参数,函数使用默认参数
- initializer_list具有默认参数的构造函数
- C++ 带有默认参数的结构,可选择在构造函数中更改
- 为什么C++构造函数在继承中需要默认参数?
- 必须非常量别名参数及其默认参数常量
- C++ 默认参数使用其他参数
- 组合函数参数包和默认参数
- 如何定义 Vector2f 的默认参数?[SFML]
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 如何设置默认参数以防用户不输入另一个参数
- 结构 c++ 中的默认参数
- 构造函数委托与默认参数
- 默认参数和函数指针作为函数参数C++
- 如何在继承层次结构中调用具有默认参数的构造函数?