Pass param packed args into a std::queue to call with a different function later

随声附和 提交于 2020-02-23 06:44:30

问题


I asked a similar question earlier without realizing that that wasn't quite specific enough.

So I have this function that has to take in all the arguments of a print function, with the ... and all, and then put it into a queue that will call the actual print function later.

Something like:

std::queue<SOMETHING> queue;
template <typename... Params>
void printLater(int a, int b, char* fmt, Params ...args) {
    queue.push(args);
}

template <typename... Params>
void print(int a, int b, char* fmt, Param ...args) {
    //whatever
}

void actuallyPrint() {
    //whatever
    print(queue.pop());
}

Context: I'm working with a piece of hardware that can only handle requests every 50ms or else they're ignored. My goal is to create a wrapper that will automatically add the delays if I send it a bunch at once.

My fallback if I cant do this, although I'd rather do this is just sprintf (or C++ equivalent) into a string only store the string in the queue and call print() without all the args.


回答1:


Something like this perhaps:

std::queue<std::function<void()>> queue;

template <typename... Params>
void printLater(int a, int b, char* fmt, Params ...args) {
    queue.push([=](){ print(a, b, fmt, args...); } );
}

void actuallyPrint() {
    queue.front()();
    queue.pop();
}


来源:https://stackoverflow.com/questions/60031355/pass-param-packed-args-into-a-stdqueue-to-call-with-a-different-function-later

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!