使用非静态值作为函数中的默认参数

Using a non static value as default argument in a function

本文关键字:函数 默认 参数 静态      更新时间:2023-10-16

有没有一种很好的方法可以将非静态值作为函数中的默认参数?我见过一些对同一问题的较早的回答,这些回答总是以明确写出过载而告终。这在 C++17 中仍然有必要吗?

我想做的是做一些类似于

class C {
  const int N; //Initialized in constructor
  void foo(int x = this->N){
    //do something
  }
}

而不必写

class C {
  const int N; //Initialized in constructor
  void foo(){
    foo(N);
  }
  void foo(int x){
    //do something
  }
}

这使得过载的目的不那么明显。

一种相对优雅的方法(在我看来(是使用 std::optional 来接受参数,如果没有提供参数,请使用对象的默认值:

class C {
  const int N_; // Initialized in constructor
    public:
    C(int x) :N_(x) {}
  void foo(std::optional<int> x = std::nullopt) {
        std::cout << x.value_or(N_) << std::endl;
  }
};
int main() {
  C c(7);
  c.foo();
  c.foo(0);
}

您可以在标准的第 11.3.6 节中找到有效/无效的完整说明。第 9 小节描述了成员访问(摘录(:

非静态成员不得出现在默认参数中,除非 显示为类成员访问表达式的 ID 表达式 (8.5.1.5( 或除非它用于形成指向成员的指针 (8.5.2.1).[示例:在以下示例中 X::mem1(( 的声明 格式不正确,因为没有为非静态提供对象 memberX::a 用作初始值设定项。

int b;
class X {
   int a;
   int mem1(int i = a);// error: non-static memberaused as default argument
   int mem2(int i = b);// OK; useX::b
   static int b;
};