簡體   English   中英

將 function 指針傳遞給模板化 class

[英]Passing a function pointer in to templated class

我的問題很簡單......我有一個模板化的二叉搜索樹。 當調用構造函數時,我需要能夠讓用戶傳入比較 function 。 我的代碼一直對我大喊大叫,直到我也將用戶定義的 function 模板化(在驅動程序中)。 這打破了我對模板如何工作的直覺。 這讓我想知道我的代碼是否沒有像我預期的那樣模板化。 I'm just curious if it is normal to have a user template their functions when declaring a class object that is templated (specially when that object requires a user defined function to be passed in). 如果這不正常,那么我知道我的代碼有問題。 在此處輸入圖像描述

這是我之前遇到的錯誤。 那些“未聲明的標識符”只是第 93 行的一個錯誤的結果。這是我試圖創建 class 實例的地方。

//Part of driver program. 
//Not sure why code doesn't work without template <typename T> 

template <typename T>
int compare(const int data, const int nodeData) 
//User defined compare function. Takes two values and compares them and returns a -1, 0, or 1 if it is less than equal to or greater than respectively. 
{
    int returnValue; //The value that will be returned. 
    if (data < nodeData)
    {
        returnValue = -1;
    }
    else if (data > nodeData)
    {
        returnValue = 1;
    }
    else
    {
        returnValue = 0;
    }
    return(returnValue);
}
//Now for the code that is inside my class. 
//The following is my decoration for the function pointer within my class.
//////////////
int (*funcCompare)(T i, T j); 
////////////////

//And lastly here is my constructor for my class 
    SplayTree(int(*compFunction)(const T, const T)) //Constructor that takes a pointer to a comparison function as an arugment. 
    {
        funcCompare = compFunction;
    };

我認為您的問題在於您對 myTree 的初始化。 我寫了一些我認為模仿你的用例的代碼。 我相信特別是最后一行將解決您的問題:

    //header file
    template <typename T>
    class TemplatedClass {
    public:
        TemplatedClass(int(*compFunction)(const T, const T)) :
            funcCompare(compFunction)
        {}
    private:
        int (*funcCompare)(const T i, const T j);
    };
    /////////////////////////////////////////////////////////////
    //compare function
    int compare(const int data, const int nodeData)
    {
        int returnValue; 
        if (data < nodeData)
        {
            returnValue = -1;
        }
        else if (data > nodeData)
        {
            returnValue = 1;
        }
        else
        {
            returnValue = 0;
        }
        return(returnValue);
    }
    //////////////////////////////////////////////////////////////
    //initialization
    TemplatedClass<int> tc(compare);

希望這可以幫助。 如果我對您的問題有誤解,請告訴我。

我相信部分問題是您的 arguments 是整數,當它們似乎應該是 T 時,以匹配用戶定義的類型。 假設它們是 int 可以進行測試,但如果需要任何其他數據類型,則不會成立。 如果是這種情況,將其模板化是有意義的,因為 function 正在有效地轉換到您的 header 文件中,該文件似乎是模板化的。 當然,我對此比較陌生,所以如果我犯了邏輯錯誤,請告訴我!

暫無
暫無

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

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