C++ Logo

std-proposals

Advanced search

[std-proposals] declfunc - parameters deduced from arguments

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Wed, 5 Jun 2024 16:08:00 +0100
Consider the following program:

    bool Func(int, float, char unsigned)
    {
        return true;
    }

    bool Func(int, float, char signed)
    {
        return false;
    }

    struct S {
        operator char signed(void) { return -1; }
    };

    int main(void)
    {
        Func( 1, 7.2f, S() );
    }

There is no overload of 'Func' that takes an 'S', and so the compiler
starts trying to convert types . . . and it sees that it can convert
an S to a signed char, and ends up invoking:

    bool Func(int, float, char signed)

Looking at the single line in 'main' that invokes 'Func', let's say we
want to get the address of the overload of 'Func' that gets invoked
when the arguments are "int&&, float&&, S&&". Well, what if we had a
new operator called 'declfunc' which could be used as follows:

    declfunc( Func(1, 7.2f, S() ) )

The operands to 'declfunc' do not get evaluated. It returns the
address of the function that would get invoked, in a function pointer
with the following type:

    bool(*)(int,float,char signed)

If you want to extract the return type and parameter types, then you can do:

    #include <tuple>

    template<typename Func>
    struct FuncTraits;

    template<typename tR, typename... tParams>
    struct FuncTraits< tR(*)(tParams...) > {
        using R = tR;
        using ParamsTuple = std::tuple< tParams... >;
    };

    int main(void)
    {
        FuncTraits< decltype(declfunc( Func(1, 7.2f, S() ) )) >::R my_retval;
        FuncTraits< decltype(declfunc( Func(1, 7.2f, S() ) ))
>::ParamsTuple my_params;
    }

The syntax of the 'declfunc' operator could either be:

    A)

        declfunc( Func(1, 7.2f, S() ) )

    B)

        declfunc( Func, 1, 7.2f, S() )

Personally I prefer Syntax A, but I'd compromise and accept Syntax B
for the sake of having access to the new feature.

Of course if 'declfunc' already exists in loads of codebases then we
would do _Declfunc or whatever.

Received on 2024-06-05 15:08:13