lundi 4 décembre 2017

Pass a lamda expression in a thread pool

I try yo compile in C++11 the following piece of code without success. My goal is to use lambda expression instead of bind in order to fill a queue with tasks. Could you please help me? Is any case to create a dangling reference ?

#include <iostream>
#include <functional>
#include <queue>
using namespace std;
std::queue<std::function<void()>> funcs;
class A
{
public:
    void foo(int a )
    {
        cout << "Hello word" << endl;
    }
};
class ThePool
{
 public:
 template<typename _Callable, typename Object, typename... _Args>
 void QueueFunction(_Callable __f, Object  obj, _Args... __args)
 { 
       funcs.push([=]()
                {
                     (obj.*__f)((__args...));
                });          
    }
    void print(int i )
    {
       cout << "Hello Word"<< i <<endl;
    }
};
int main(int argc, char** argv) {
ThePool t;
A a ;
t.QueueFunction(&A::foo,a,5);
std::function<void()> func = funcs.back();
func();
return 0;
}

The error that is generated is the following

main.cpp:24:38: error: parameter packs not expanded with '...': (obj.__f)((__args...)); ^ main.cpp:24:38: note: '__args' main.cpp:24:44: error: expected ')' before '...' token (obj.__f)((__args...)); ^ main.cpp:24:49: error: expected ')' before ';' token (obj.*__f)((__args...)); ^ main.cpp: In function 'int main(int, char**)': main.cpp:39:45: error: conversion from 'std::function' to non-scalar type 'std::function' requested std::function func = funcs.back(); ^ main.cpp: In instantiation of 'struct ThePool::QueueFunction(_Callable, Object, _Args ...) [with _Callable = void (A::)(int); Object = A; _Args = {int}]::__lambda0': main.cpp:22:12: required from 'void ThePool::QueueFunction(_Callable, Object, _Args ...) [with _Callable = void (A::)(int); Object = A; _Args = {int}]' main.cpp:38:32:
required from here main.cpp:24:38: error: using invalid field 'ThePool::QueueFunction(_Callable, Object, _Args ...)::__lambda0::____args' (obj.*__f)((__args...));

Aucun commentaire:

Enregistrer un commentaire