Overload function when passing lambda as parameter

I am trying to implement a template function when the return parameter is either void or T. I tried the various code options above using sfinae, but still not sure if this is possible at all if lamdba is a function parameter. The following code does not compile:

#include <functional>

template <typename T>
T Apply(const std::function<T()>& func)
{
    return func();
}

template <>
void Apply(const std::function<void()>& func)
{
    func();
}

int main(int argc, char *argv[])
{
    int i1 = Apply([]() { return 10; });
    bool b1 = Apply([]() { return true; });
    Apply([]() { return; });

    return 0;
}

Error:

error C2672: 'Apply': no matching overloaded function found
error C2784: 'T Apply(const std::function<T(void)> &)': could not deduce     template argument for 'const std::function<T(void)> &' from 'main::<lambda_536cc9cae26ef6d0d1fbeb7b66a2e26b>'

wandbox live

+4
source share
2 answers

This is due to the fact that template subtraction requires a perfect match for each of the function arguments in order to successfully display the template parameters.

You will need to set the object of the object itself:

#include <type_traits>

template <class Function, class Return = std::result_of_t<Function()>>
Return Apply(Function func)
{
    return func();
}

Using:

#include <iostream>

int main()
{
    std::cout << Apply([]() { return 42; }) << "\n";
}

live demonstration

+3
source

, , ( std::function) ; , T .

auto, . .

template <typename T>
auto Apply(T func)
{
    return func();
}

LIVE

+4

Source: https://habr.com/ru/post/1692645/


All Articles