C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Initializing std::function with overload sets

From: Julien Villemure-Fréchette <julien.villemure_at_[hidden]>
Date: Thu, 27 Feb 2025 11:49:37 -0500
You could also force overloaded resolution to happen by copy initialization a reference and then use the reference to construct the std::function:

void func(int); // overload 1
void func(double); // overload 2

void (&fir)(int) = func; // selects 1
std::function fi = fir;

void (&fdr)(double) = func; // selects 2
std::function fd = fdr;

If the overload set named by 'func' could be used at different places in code (ex, to initialize more std::function), then the reference variables 'fir' and 'fdr' may also be declared in a wide enough scope so that they can be referred to. This way you only perform overload resolution once, at the time of reference initialization, and avoid the need for using casts.

On the other hand, if you want to limit the scope of the reference variables 'fir' and 'fdr', then you can wrap the std::function initialization in an immediate lambda:

auto fi = []
{
    void (&fir)(int) = func; // selects 1
    return std::function{fir};
}();

auto fd = []
{
    void (&fdr)(double) = func; // selects 2
    return std::function{fdr};
}();



On February 27, 2025 9:15:51 a.m. EST, Bjorn Reese via Std-Proposals <std-proposals_at_[hidden]> wrote:
>On 2/27/25 03:38, Jack O'Donohue via Std-Proposals wrote:
>> I noticed that unlike when initializing function pointers, std::function (and copyable_function, etc.) can't select the right overload of a function when it is initialized. For example,
>
>The core problem is not std::function, but rather overloaded functions.
>The same problem occurs when we pass an overloaded function as argument
>to another function, such as std::apply.
>
>A solution to this problem is to wrap the overloaded function as a
>function object (similar to std::plus etc.)
>
> inline constexpr struct {
> template <typename... Args>
> auto operator()(Args&&... args) const {
> return add(forward<Args>(args)...);
> }
> } my_add{};
>
>It is possible to create macros for this, such as
>
>
>https://www.boost.org/doc/libs/release/libs/hof/doc/html/include/boost/hof/lift.html
>
>Hopefully reflection will enable us to lift overloaded functions
>directly.
>
>--
>Std-Proposals mailing list
>Std-Proposals_at_[hidden]
>https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2025-02-27 16:49:48