1

I'm trying to make a function which takes any function returning void and generating a function returning bool by simply calling the original function and returning false.

template<typename Arg>
auto voidToBoolTemplate(std::function<void(Arg)> func)
{
    return [&](Arg arg)
    {
        func(arg);
        return false;
    };
}

However, I'm having trouble passing lambdas to this function.

auto lambda = [](int x)
{
    std::cout << x << '\n';
};

voidToBoolTemplate(lambda);

This is the error I get with clang 3.7.0:

Error(s):
source_file.cpp:32:5: error: no matching function for call to 'voidToBoolTemplate'
    voidToBoolTemplate(lambda);
    ^~~~~~~~~~~~~~~~~~
source_file.cpp:5:6: note: candidate template ignored: could not match 'function<void (type-parameter-0-0)>' against '(lambda at source_file.cpp:25:19)'
auto voidToBoolTemplate(std::function<void(Arg)> func)

Assigning the lambda to std::function and then calling the function works.

auto lambda = [](int x)
{
    std::cout << x << '\n';
};

std::function<void(int)> foo = lambda;

voidToBoolTemplate(foo);

In addition, if I use a specific type for the argument I can pass a lambda:

auto voidToBoolNonTemplate(std::function<void(int)> func)
{
    return [&](int arg)
    {
        func(arg);
        return false;
    };
}

auto lambda = [](int x)
{
    std::cout << x << '\n';
};

voidToBoolNonTemplate(lambda);

Can anyone explain this behavior?

A live demo: http://rextester.com/COKT94318

Dvir Yitzchaki
  • 487
  • 4
  • 13
  • Thanks, apparently my searching capabilities are not as good as I thought. – Dvir Yitzchaki Oct 10 '16 at 10:26
  • Do you really want to convert the lambda to a `std::function` though? In this case you want to convert one lambda to another lambda. – Chris Drew Oct 10 '16 at 10:35
  • As demonstrated in the linked question, inferring the arguments to a lambda is hard. But if you don't mind specifying the type at the point you call `voidToBoolTemplate` you can just make the `Arg` (or `Args...`) another template parameter that needs to be specified: http://melpon.org/wandbox/permlink/QBrYUC46WIJLtdfD – Chris Drew Oct 10 '16 at 11:01
  • @ChrisDrew can I convert it to a lambda without auto return type dedcution? I need to support pre C++14 compiler. – Dvir Yitzchaki Oct 10 '16 at 11:18

0 Answers0