簡體   English   中英

C ++模板類函數作為模板參數

[英]C++ Template class function as template parameter

在某種程度上,實現需要像標准模板庫的優先級隊列那樣起作用的類(就模板部分而言)的正確方法是什么,因為我需要創建一個數據結構(針對具有常規模板的類型進行參數化) ,並且這部分還可以),但另外還有一個我想作為模板參數傳遞的比較函數。 如何實施? 謝謝

編輯:請求的偽代碼(在注釋中)

template <class T, "syntax for the compare function?">
class myclass
{ 
'I have to refer in some way to the compare function here?'
... }

myclass:: myfunctionusingcomparefunction(){
  if('how to use the compare function here?'){...
}else{...}
}

EDIT2:更好的解釋

我要問的是如何實現能夠與模板類型的元素進行比較(或應用函數)的類。 我之所以提到標准模板類的優先級隊列類,是因為它允許選擇一個重寫operator()的模板類來比較元素(在有序插入中是必需的):在std :: priority_list情況下,第二個模板參數是比較器類。

priority_list<ObjectType, ObjectComparatorType> myQueue;

基本上,只需具有比較函數類型的成員,並具有對該類型的引用的構造函數,以便可以根據需要向對象傳遞函數指針/ lambda / std::function 這是GNU libstdc ++為std::priority_queue (不相關的位被刪除)執行的操作:

template <class _Tp, class _Sequence = vector<_Tp>, 
          class _Compare = less<typename _Sequence::value_type> >
class  priority_queue {
protected:
  _Sequence c;
  _Compare comp;
public:
  explicit priority_queue(const _Compare& __x) :  c(), comp(__x) {}

好的,考慮優先級列表的示例,可以為我的問題提供以下解決方案:我的模板類采用三個模板參數,priority_queue對象的類型,優先級對象的類型和必須覆蓋operator()比較優先級對象。 比較器類的對象在比較器類中給出,在構造函數中給出

priorityQueue.hpp

template <class T, class Prio, class Comp>
class priorityQueue{
    template <class T, class Prio>
    class Node{
        T elem;
        Node *next;
        Prio priority;

        public:
        Node(T e, int p) : elem(e), priority(p) {}
    };

    /*class priorityExc{
    public:
        const char* what(){ return "Priority must be in [0, 10]";}
    };*/

    class emptyExc{
    public:
        const char* what(){ return "No element to remove";}
    };


    Node<T, Prio> *head;
    int len;
    Comp comparator; //must overload the operator()

    public:
    priorityQueue(Comp cmp) : comparator(cmp), len(0) {}
    void insert (T myElem, Prio myPriority);// throw (priorityExc);
    T remove() throw (emptyExc);
};

使用這種方法,可以以以下優先級方式將元素插入隊列中的insert方法的實現:

template <class T, class Prio, class Comp>
void priorityQueue<T, Prio, Comp>::insert(T myElem, Prio myPriority) //throw (priorityExc)
{
    //if(myPriority > 10 || myPriority < 0) throw priorityExc;
    Node<T, Prio> *node = new Node(myElem, myPriority);
    if(head == 0){
        head = node;
        head->next = 0;
    }
    else{
        Node *temp = head, *p = head;
        while(comparator(temp->priority, node->priority) > 0){
            p = temp;
            temp = temp->next;
        }
        p->next = node;
        node->next = temp;
    }
}

暫無
暫無

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

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