Home > Mobile >  How to pass a struct member in one of the struct's method as default parameter?
How to pass a struct member in one of the struct's method as default parameter?

Time:02-01

I want to pass the variable a as a default parameter in method func().

struct S {
    int a;
    int func(int b = a) {
        // do something
    }
};

On compiling it shows error. Is it possible to somehow get around this?

CodePudding user response:

It is not possible to use the value of a non-static member as default argument. You can use an overload instead:

struct S {
    int a;
    int func(int b) {
        // do something
    }
    int func() { return func(a); }
};

CodePudding user response:

Another alternative is to use std::optional:

struct S {
    int a;
    int func(std::optional<int> ob = std::nullopt) {
        int b = ob.value_or(a);
        // do something
    }
};
  •  Tags:  
  • Related