0

In provided example foo cannot infer type of T for both - function pointer and lambda (commented out), with provided type or foo2 everything works fine. What prevents foo from infering type T? Is there any way to have it done autmatically?

template<typename T>
void foo(std::function<T(const T&)> op) {
    std::cout << op(6) << std::endl;
}

void foo2(std::function<int(const int&)> op) {
    std::cout << op(6) << std::endl;
}

int bar(const int &x) {return 3 * x;}

int main() {
    //    foo(bar);
    //    foo([](const int &x) {return 3 * x;});

    foo<int>(bar);
    foo<int>([](const int &x) {return 3 * x;});

    foo2(bar);
    foo2([](const int &x) {return 3 * x;});

    return 0;
}
Krzysztof
  • 769
  • 8
  • 27
  • Well, deduction won't work in this case because the value you pass to function in both cases must be (implicitly) converted to the value expected by function. Note that this conversion can not happen *before* type of `std::function` specialization is deduced like `bar` -> `::std::function` -> `T` is `int`. Also it does not make much sense to accept an `std::function` instance, just accept a callable object. – user7860670 Jan 30 '18 at 19:52
  • What prevents the type deduction is the fact that the lambda is an unrelated type with `std::function<>`. A solution is to go all the way to a fully templated function. It is a pity the question was closed because I had a concrete solution simpler and more specific than in the linked answers of the duplicate. – alfC Jan 30 '18 at 19:53
  • Do this `template void foo2(T&& op) { std::cout << op(6) << std::endl; }` – alfC Jan 30 '18 at 19:56
  • @alfC OK - deduction with lambda is a problem here, but what about 'bar' function? – Krzysztof Jan 30 '18 at 19:59
  • 1
    @Krzysztof, it is the same story, the type of `bar` int(*)(const int&)` is unrelated with `std::function`. If you want this to work my solution above is an option even for `bar`. Otherwise you can overload `foo2(int(*op)(const int&){...}` or something like that. – alfC Jan 30 '18 at 20:00

0 Answers0