C++ Logo

std-proposals

Advanced search

[std-proposals] std::function with default arguments

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sat, 1 Mar 2025 20:55:14 +0000
Consider if the following were possible:

    #include <functional>

    int Func(int a, int b = 6, int c = 7)
    {
        return a + b + c;
    }

    int main(void)
    {
        std::function f = Func;

        f(5);
        f(5,4);
        f(5,4,3);
    }

Dissecting the above code . . . it would have to work something like as follows:

Point No. 1) When the object 'f' is created, it would have to be of
type std::function<int(int,int,int)>

Point No. 2) An object of type std::function<int(int,int,int)> must
internally contain space for three default values needed to be used as
default arguments

Point No. 3) Compile support (aka compiler magic) would be needed when
'f' is initialised (or assigned to) in order to populate the default
arguments

Point No. 4) Given that 'f' can later be reassigned, there must be
accommodated, situations in which the default arguments are missing,
so throw an exception of type std::missing_def_args

I used std::function in the above example, but Point No. 2 would cause
an ABI break and so there would have to be a new standard library
class called something like std::function_defargs.

With regard to Point No. 4, we could have code like:

    #include <functional>

    int Func(int a, int b = 6, int c = 7)
    {
        return a + b + c;
    }

    int SomeOtherFunc(int a, int b, int c)
    {
        return 666;
    }

    int main(void)
    {
        std::function_defargs f = Func;

        f(5);
        f(5,6);
        f(5,6,7);

        f = SomeOtherFunc;
        f(5);
    }

That last line in 'main' would throw an exception of type std::missing_def_args.

The class 'function_defargs" is writeable in current C++ except for
needing compiler support to garner the default arguments from the
declaration of the assigned-from function.

Plus it would be possible to manually manipulate the default
arguments, for example:

        f = SomeOtherFunc;
        f.set_arg(1) = 4;
        f.set_arg(2) = 3;
        f(5); // This line no longer throws

Received on 2025-03-01 20:55:25