将参数打包的 args 传递到 std::queue 以便稍后使用不同的函数调用

我之前问过一个类似的问题,但没有意识到这不够具体.

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.

类似:

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());
}

上下文:我正在使用只能每 50 毫秒处理一次请求的硬件,否则它们会被忽略.我的目标是创建一个包装器,如果我一次发送一堆,它会自动添加延迟.

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.

如果我不能这样做,我的后备,虽然我宁愿这样做只是 sprintf(或 C++ 等价物)到一个字符串中,只将字符串存储在队列中并调用 print() 没有所有参数.

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.

推荐答案

可能是这样的:

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();
}

相关文章