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

Using a non static value as default argument in a function

有没有什么好的方法可以将非静态值作为函数中的默认参数?我见过一些对同一个问题的较早的回答,这些回答总是以显式写出重载而告终。这在 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 节中找到 works/doesn 无效内容的完整解释。第 9 小节描述了成员访问(摘录):

A non-static member shall not appear in a default argument unless it appears as the id-expressionof a class member access expression (8.5.1.5) or unless it is used to form a pointer to member (8.5.2.1).[Example:The declaration of X::mem1()in the following example is ill-formed because no object is supplied for the non-static memberX::a used as an initializer.

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;
};