DeinFreund
DeinFreund

Reputation: 97

Using a non static value as default argument in a function

Is there a nice way to have a non static value as default argument in a function? I've seen some older responses to the same question which always end up in explicitly writing out the overload. Is this still necessary in C++17?

What I'd like to do is do something akin to

class C {
  const int N; //Initialized in constructor

  void foo(int x = this->N){
    //do something
  }
}

instead of having to write

class C {
  const int N; //Initialized in constructor

  void foo(){
    foo(N);
  }

  void foo(int x){
    //do something
  }
}

which makes the purpose of the overload less obvious.

Upvotes: 3

Views: 102

Answers (1)

midor
midor

Reputation: 5557

One relatively elegant way (in my opinion) would be to use std::optional to accept the argument, and if no argument was provided, use the default from the object:

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

You can find the full explanation of what works/doesn't work in section 11.3.6 of the standard. Subsection 9 describes member access (excerpt):

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

Upvotes: 2

Related Questions