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/8178392/

相关文章:

c++ - 未定义的枚举引用

c++ - 如何从文件中读取 double 值?

C++11,常量数据成员,std::inserter,复制

java - 相机崩溃 : Fatal signal 6 (SIGABRT) with JNI code

C++ 使用 ofstream 写入二进制文件

c++ - [[attributes]] 是 C++11 的新功能吗?

c++ - 为任何 vector 编写 operator<< 的模板

c++ - 为什么第一个程序不起作用但第二个程序有效?第二,为什么输出是它给出的?

scala - 在 Scala 中重载泛型方法

c++ - 向类添加复制构造函数