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

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

本文关键字:函数调用 参数 参数传递 queue std      更新时间:2023-10-16

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

所以我有这个函数,它必须接受打印函数的所有参数,与...,然后将其放入稍后将调用实际打印函数的队列中。

像这样:

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 毫秒处理一次请求,否则它们将被忽略。我的目标是创建一个包装器,如果我一次发送一堆,它会自动添加延迟。

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

也许是这样的:

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