【问题标题】:compiler determine argument is given or omitted编译器确定参数是给定还是省略
【发布时间】:2019-12-10 06:46:28
【问题描述】:

如何在编译时确定/检查函数参数是否给出或省略?

bool a_function(char* b, size_t len=0) {

      // no run time check such as if (len ......
      // just compile time check

      // ...
}

如何实现?

【问题讨论】:

  • 你写了 2 个不同的函数...
  • 它们总是被提供——调用者使用函数声明中给出的默认值,然后以正常方式调用函数。

标签: c++ function default-arguments


【解决方案1】:

不,没有办法知道(即使在运行时)是否为函数中具有默认参数的参数指定了参数。

你可以应用重载,例如

bool a_function(char* b, size_t len) {

    // len is specified
    // do something...
}
bool a_function(char* b) {

    // len is not specified
    // do something else...
    // or call a_function with len=0 (the default value) if satisfying the requirement
}

【讨论】:

  • ...并且,为了减少可能的代码重复,在以某种方式确定 len 之后,第二个函数仍然可以调用第一个函数。
  • 是的,默认参数是(大部分/完全?)用于将这两个函数组合成一个函数的语法糖,特别是适用于您不关心是否参数是否默认。不使用这种语法糖正是这里所要求的。
猜你喜欢
  • 1970-01-01
  • 2014-03-07
  • 2017-01-15
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
  • 2015-06-06
  • 1970-01-01
相关资源
最近更新 更多