Is it possible to use member function call as default argument?

Viewed 3378

Here is my code:

struct S
{
   int f() { return 1; }
   int g(int arg = f()) { return arg; }
};

int main()
{
    S s;
    return s.g();
}

This fails to compile with the error:

error: cannot call member function 'int S::f()' without object

Trying this->f() doesn't work either, as this may not be used in that context.

Is there a way to make this work, still using the default argument?


Of course it can be worked around by not using default arguments at all:

int g(int arg) { return arg; }
int g() { return g(f()); }

however that gets verbose considering that in the "real code" there are more parameters before arg, and several functions following this pattern. (And even more ugly if there were multiple default arguments in the one function).

NB. This question looks similar at first, but in fact he is asking how to form a closure, which is a different problem (and the linked solution doesn't apply to my situation).

3 Answers
Related