How to pass a template function as an argument and automatically deduce its type

100 Views Asked by At

Let's consider the following example. As we can see, global_op and local_op do absolutely the same things. But the local_op type is deduced, while the global_op type is not. So I want to ask if it is possible to pass a global template function as an argument without specifying its type and wrapping it in a lambda.

#include <iostream>

auto func(auto&& operation) { return operation(1, 2); }
auto global_op(auto&& x, auto&& y) { return x + y; }

int main()
{
    auto local_op = [](auto&& x, auto&& y) { return x + y; };
    auto local_op_2 = [](auto&& x, auto&& y) { return global_op(x, y); };

    std::cout << func(local_op) << std::endl;             // OK
    //std::cout << func(global_op)<< std::endl;           // not working!
    std::cout << func(global_op<int, int>) << std::endl;  // work, but you MUST specify type, that func using internally (and you can not know that type)
    std::cout << func(local_op_2) << std::endl;           // OK, by you need to wrap function to lambda!

    return 0;
}
0

There are 0 best solutions below