gpt4 book ai didi

c++ - 如何在 C++ 中创建函数指针队列

转载 作者:行者123 更新时间:2023-11-30 01:46:28 25 4
gpt4 key购买 nike

我正在尝试使用 C++ 创建协作调度程序,为此我需要一个包含函数指针的队列。

C++ 队列 STL 库在这方面有帮助吗?

最佳答案

这显然正是 std::queue 旨在帮助解决的问题类型。

虽然我会改变一些事情。一种是存储 std::function 而不是指向函数的原始指针:

struct task {
int id;
std::function<void()> f;
};

这允许您传递基本上任何可以像函数一样调用的东西,而不仅仅是指向实际函数的指针。对于一个明显的例子,您可以使用 lambda 表达式:

    task t { 1, [] {cout << "having fun!\n"; } };  
q.push(t);
auto tsk = q.front();
tsk.f();

由于任务几乎唯一能做的就是调用它,我还考虑为 task 提供重载的 operator() 来执行调用: void operator()() { f(); },所以如果你只想调用一个任务,你可以这样做:

auto f = q.front();
f();

您的测试程序扩展为包括这些可能看起来更像这样:

#include <iostream>
#include <queue>
#include <functional>

using namespace std;

struct task {
int id;
std::function<void()> f;

void operator()() { f(); }
};

queue<struct task> q;

void fun(void) {
cout << "Having fun!" << endl;
}

int main() {

cout << "Creating a task object" << endl;

task t;
t.id = 1;
t.f = &fun;

cout << "Calling function directly from object" << endl;
t.f();

cout << "adding the task into the queue" << endl;
q.push(t);

cout << "calling the function from the queue" << endl;
task tsk = q.front();
tsk.f();
q.pop();

q.push({ 1, [] {std::cout << "Even more fun\n"; } });

auto t2 = q.front();
t2.f(); // invoke conventionally

t2(); // invoke via operator()

q.pop();
}

关于c++ - 如何在 C++ 中创建函数指针队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33204974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com