Home > Net >  Passing a lambda to a template function taking a std::function as parameter
Passing a lambda to a template function taking a std::function as parameter

Time:09-29

I have a template function taking a std::function parameter, the template arguments defining function signature:

template<typename... Args>
void addController(const char * name, const std::function<bool(Args...)> & func);

It works passing a std::function variable:

std::function<bool()> foo_func = [this]()->bool {return this->isFoo(); };
addController<>("foo", foo_func);  //Works

But if I pass the lambda directly, it fails deducing the type:

//Fails to compile
addController<>("foo", [this]()->bool {return this->isFoo(); });

And using a non template function works:

void addControllerNoArg(const char * name, std::function<bool()> func);
addControllerNoArg("foo", [this]() {return this->isFoo(); });  //Works

I need the <typename... Args> template for unwrapping a variant vector argument tables into the function call. This actually does work in the implementation, the only issue is I can't pass a lambda to addController directly.

Minimal example: https://onlinegdb.com/MS1cEreKhk

CodePudding user response:

Way to go is generic callable:

template<typename F>
void addController(const char* name, F f)

You can forward it to your std::function version if needed:

template <typename... Args>
void addController(const char* name, const std::function<bool(Args...)> & func)
{
   /*..*/
}

template <typename F>
void addController(const char* name, F f)
{
    addController(name, std::function{f}); // CTAD used, so C  17 required
}
  • Related