Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic template method and std::function - compilation error [duplicate]

I'm sure the error is very simple and silly, but I can't see one. Here's the code:

#include <future>

template <typename ResultType>
class Foo
{
public:
    template <typename ...Args>
    void exec(const std::function<ResultType(Args...)>& task, Args&&... args) {}
};

int main()
{
   Foo<void>().exec([](){});
   return 0;
}

And here's the error:

'void CAsyncTask::exec(const std::function &,Args &&...)' : could not deduce template argument for 'const std::function &' with [ ResultType=void ]

Foo<void>().exec<void>([](){}) doesn't work either (and I'd much prefer not having to specify the Args types manually).

Update regarding the suggested answer: the following code does indeed work. CAsyncTask<void>().exec(std::function<void ()>([](){}));

But is there really no workaround for this problem? Can I expand my template somehow to deduce the lambda arguments?

like image 578
Violet Giraffe Avatar asked May 01 '26 21:05

Violet Giraffe


1 Answers

You could try changing exec's signature to

template<typename Fn, typename... Args> 
void exec(Fn&& task, Args&&... args)

and then construct your std::function inside the function

like image 185
KABoissonneault Avatar answered May 03 '26 12:05

KABoissonneault