Why does automatic template deduction fail?

  c++, templates

I’ve already asked a similar question here: Why does automatic type deduction fail?

However, I think I stripped down the code example too much in order to make a minimal working example. It does not reflect the problem I am facing.

Consider the code below. Why is it needed to add <int, std::string> as template arguments? Shouldn’t the compiler be able to deduce this from fn_myfunc itself?

#include <functional>
#include <string>


template <class In, class Out>
class MyClass{
public:
    MyClass(
        std::function<Out (In)> process
    ) :
        process_(process)
    {
    }
private:
    std::function<Out (In)> process_;
};

std::string myfunc(int in) {
    return std::to_string(in);
}

int main(int argc, char * * argv) {
    std::function<std::string (int)> fn_myfunc = myfunc;
    MyClass<int, std::string> instance(fn_myfunc);
    return 0;
}

Source: Windows Questions C++

LEAVE A COMMENT