MAJOR EDIT TO SIMPLIFY CODE (and solved)
I would like to be able to make a packaged task that has a free unbound argument, which I will then add at call time of the packaged task.
In this case, I want the first argument to the function (of type size_t
) to be unbound.
Here is a working minimal example (this was the solution):
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
#include <cstdlib>
#include <cstdio>
//REV: I'm trying to "trick" this into for double testfunct( size_t arg1, double arg2), take enqueue( testfunct, 1.0 ), and then internally, execute
// return testfunct( internal_size_t, 1.0 )
template<typename F, typename... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(size_t, Args...)>::type>
{
using return_type = typename std::result_of<F(size_t, Args...)>::type;
//REV: this is where the error was, I was being stupid and thinking this task_contents which would be pushed to the queue should be same (return?) type as original function? Changed to auto and everything worked... (taking into account Jans's result_type(size_t) advice into account.
//std::function<void(size_t)> task_contents = std::bind( std::forward<F>(f), std::placeholders::_1, std::forward<Args>(args)... );
auto task_contents = std::bind( std::forward<F>(f), std::placeholders::_1, std::forward<Args>(args)... );
std::packaged_task<return_type(size_t)> rawtask(
task_contents );
std::future<return_type> res = rawtask.get_future();
size_t arbitrary_i = 10;
rawtask(arbitrary_i);
return res;
}
double testfunct( size_t threadidx, double& arg1 )
{
fprintf(stdout, "Double %lf Executing on thread %ld\n", arg1, threadidx );
std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
return 10; //true;
}
int main()
{
std::vector<std::future<double>> myfutures;
for(size_t x=0; x<100; ++x)
{
double a=x*10;
myfutures.push_back(
enqueue( testfunct, std::ref(a) )
);
}
for(size_t x=0; x<100; ++x)
{
double r = myfutures[x].get();
fprintf(stdout, "Got %ld: %f\n", x, r );
}
}