本文介绍了如何清楚地指定我传递哪些参数,哪些是默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为这个问题

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

Say I have a function such as this: void f(int p1=1, int p2=2, int p3=3, int p4=4);

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

And I want to call it using only some of the arguments - the rest will be the defaults.

这样的工作方式:

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

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

But it requires too much code to be practical.

有更好的方法吗?

推荐答案

命名参数惯用(→ )也可以解决这个任务,但是通过代码冗长付费,大大降低了清晰度。它在处理构造函数方面也有缺陷。当然,它需要安装Boost库。

The Boost.Parameters library (→ link) can also solve this task, but paid for by code verbosity and greatly reduced clarity. It's also deficient in handling constructors. And it requires having the Boost library installed, of course.

干杯& hth。,

Cheers & hth.,

这篇关于如何清楚地指定我传递哪些参数,哪些是默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:52