簡體   English   中英

functor:在類中包裝std :: function

[英]functor: wrapping std::function in a class

假設我正在編寫一個應該提供一些默認計算(功能)的庫,但允許用戶在編譯時提供自己的庫。 例如,假設該庫提供了一個函數,該函數返回其參數乘以3,但是用戶可以提供自己的函數。

考慮以下程序(被視為MWE):

float myFunction( float v )  // the function the user needs
{
    return v*2;
}

int main()
{
    FuncWrapper f;
    cout << "default: " << f(2) << endl; // should print "6"

    f.AssignFunction( myFunction );
    cout << "now is: " << f(2) << endl; // should print "4"
}

因此,我已經構建了一個包裝std::function FuncWrapper函數FuncWrapper也可以在這里提出:

struct FuncWrapper
{
    std::function<float(float)> foo; // the function used

    float def( float v ) // the default behaviour member function definition
    {
        return v*3;
    }

    float operator()( float v ) // call of function
    {
        return foo(v);
    }

    void AssignFunction( float (*uf)(float) ) { foo = uf; }

// constructor: initializes to default function
    FuncWrapper() : foo(&FuncWrapper::def) {}
};

在我的具有-std=c++0x機器(gcc 4.6.3)上,我收到了人類無法理解的錯誤消息,如其他答案所述 為了方便起見,代碼可在此處運行 似乎是gcc 4.8,它不喜歡構造函數(除其他錯誤外……):

main.cpp: In constructor 'FuncWrapper::FuncWrapper()':
main.cpp:27:64: error: no matching function for call to 'std::function<float(float)>::function(float (FuncWrapper::*)(float))'

為什么這種分配是非法的? 我已經搜索了這個主題,也許是錯誤的關鍵字,但是沒有找到任何相關的內容。

有什么線索嗎? 或更簡單的解決方案,也許沒有std::function但帶有函數指針?

在示例代碼中,您嘗試將成員函數分配給具有簽名float(float)std::function 這兩個不兼容,因為成員函數具有不同的調用約定:它需要this參數。

為避免這種情況,請將默認函數設為static

暫無
暫無

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

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