簡體   English   中英

如何在C ++中創建函數指針隊列

[英]How to create a queue of function pointers in C++

我正在嘗試使用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(); } 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();
}

似乎我找到了一種使用結構來實現功能隊列的簡單方法。 可能不是完美的或高效的,目前就行了。

#include <iostream>
#include <queue>

using namespace std;

struct task {
    int id;
    void (*fptr) (void);
};

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.fptr = &fun;

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

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

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

    return 0;

}


OUTPUT : 

Creating a task object
Calling function directly from object
Having fun!
adding the task into the queue
calling the function from the queue
Having fun!

我不會使用std :: queue格式中描述的隊列。

它不允許您在任何給定位置插入。 您應該建立自己的。

如果像下面這樣操作並添加優先級和名稱,那么您可以輕松地提出邏輯來切換任務,切換/更新優先級,甚至插入所需的位置。

我會說鏈表總是有速度問題。 您還可以對結構數組執行類似的操作,並使用數組邏輯來移動和插入。

struct function_T {
    string name;
    uint8_t priority;
    void(*func_ptr)(void);
};

struct node_T {
    node_T * previous = NULL;
    function_T fptr;
    node_T * next;
};

int main(void){

    function_T task1;
    task1.name = "task1";
    task1.priority = 1;
    task1.func_ptr = func4;

    node_T first_node;
    first_node.previous = NULL;
    first_node.fptr = task1;
    first_node.next = NULL;

    first_node.fptr.func_ptr();
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM