Search code examples
c++templatesstd-functiontemplate-argument-deduction

Deduce template argument from std::function call signature


Consider this template function:

template<typename ReturnT>
ReturnT foo(const std::function<ReturnT ()>& fun)
{
    return fun();
}

Why isn't it possible for the compiler to deduce ReturnT from the passed call signature?

bool bar() { /* ... */ }

foo<bool>(bar); // works
foo(bar); // error: no matching function call

Solution

  • std::function<bool()> bar;
    
    foo(bar); // works just fine
    

    C++ can't deduce the return type from your function bar because it would have to know the type before it could find all the constructors that take your function pointer.

    For example, who's to say that std::function<std::string()> doesn't have a constructor taking a bool (*)()?