2

Is there any way to pass a lambda to a function template which takes a std::function<void(T)> argument, and have the T template parameter deduced from the argument of the lambda, rather than having to explicitly state it?

That is, given a lambda of the form [](std::string){...}, deduce T is std::string?

Example:

So with a function template

template<typename T>
void func(std::function<void(T)> f) { ... }

I can call func by explicitly specifying std::string as follows:

func<std::string>([](std::string){...});

I would like to deduce std::string, and call func as follows:

func([](std::string){...});

Examplar app below:

#include <iostream>
#include <functional>

template<typename T>
void func(std::function<void(const T&)> f)
{
    T m = "hello world";
    f(m);
}

struct foo
{
    void bar(std::string msg)
    {
        std::cout << __func__ << ": " << msg << std::endl;
    }
};

int main()
{
    foo f;

    // explicit specification works
    func<std::string>([&](const std::string& m) {
        f.bar(m);
    });

    // relying on argument deduction fails
//  func([&](const std::string& m) {
//      f.bar(m);
//  });

    return 0;
}
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213

0 Answers0