Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a lambda to a template function taking a std::function as parameter

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

like image 558
galinette Avatar asked Dec 06 '25 17:12

galinette


1 Answers

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
}
like image 185
Jarod42 Avatar answered Dec 08 '25 07:12

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!