c++ - 我怎样才能清楚地指定我要传递哪些参数以及哪些参数保持默认?

标签 c++ c++11 overloading default-arguments

因此询问:Default argument in c++

假设我有这样一个函数:void f(int p1=1, int p2=2, int p3=3, int p4=4);

我只想使用一些参数来调用它——其余的将是默认值。

像这样的东西会起作用:

template<bool P1=true, bool P2=true, bool P3=true, bool P4=true>
void f(int p1=1, int p2=2, int p3=3, int p4=4);
// specialize:
template<>
void f<false, true, false, false>(int p1) {
  f(1, p1);
}
template<>
void f<false, true, true, false>(int p1, int p2) {
  f(1, p1, p2);
}
// ... and so on. 
// Would need a specialization for each combination of arguments
// which is very tedious and error-prone

// Use:
f<false, true, false, false>(5); // passes 5 as p2 argument

但是它需要太多的代码才能实用。

有更好的方法吗?

最佳答案

使用命名参数习语(→ FAQ link)。

Boost.Parameters 库(→ link )也可以解决此任务,但代价是代码冗长且清晰度大大降低。它在处理构造函数方面也存在不足。当然,它需要安装 Boost 库。

关于c++ - 我怎样才能清楚地指定我要传递哪些参数以及哪些参数保持默认?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27001579/

相关文章:

c++ - 通过函数参数而不是模板参数获取元组的元素

c++ - G++ 4.6 -std=gnu++0x : Static Local Variable Constructor Call Timing and Thread Safety

c++ - 使用通用引用实现前向函数

c++ - Operator<< 重载,endl导致segmentation fault

C++ - ostream、 friend 和命名空间

c++ - 我可以显式调用复制构造函数吗?

python - 错误 : Microsoft Visual C++ 10. 0 是必需的(无法找到 vcvarsall.bat)。在 Windows 10 64 位上安装 Scrapy 时

c++ - 编译器的健壮性……天真

c++ - 转发引用 : returning T when given T&& and T& when given T&

C# 方法重载和泛型接口(interface)