簡體   English   中英

無法std :: bind成員函數

[英]Unable to std::bind member function

我寫了以下課程:

class SomeClass {
private:
    void test_function(int a, size_t & b, const int & c) {
        b = a + reinterpret_cast<size_t>(&c);
    }
public:
    SomeClass() {
        int a = 17;
        size_t b = 0;
        int c = 42;
        auto test = std::bind(&SomeClass::test_function, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
        test(a, b, c);
    }
}

就其本身而言,這段代碼在IDE(Visual Studio 2015)中看起來很好,但是當我嘗試編譯它時,我收到以下錯誤:

Error   C2893   Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'    Basic Server    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\type_traits  1441    
Error   C2672   'std::invoke': no matching overloaded function found    Basic Server    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\type_traits  1441    

我究竟做錯了什么?

編輯:我也寫了這個版本:

class SomeClass {
private:
    void test_function(int a, size_t & b, const int & c) {
        b = a + reinterpret_cast<size_t>(&c);
    }
public:
    SomeClass() {
        int a = 17;
        size_t b = 0;
        int c = 42;
        auto test = std::bind(&SomeClass::test_function, a, std::placeholders::_1, std::placeholders::_2);
        test(b, c);
    }
}

我得到完全相同的錯誤。

您忘記了std::bind的第四個參數,那就是您要在其上調用非靜態成員函數的實例。 因為它不對(不存在的)類成員數據進行操作,所以我認為它應該是static ,在這種情況下你不需要實例。

話雖這么說,如果你想綁定到非靜態成員函數,你可以這樣做:

auto test = std::bind(&SomeClass::test_function, this, std::placeholders::_1,
                      std::placeholders::_2, std::placeholders::_3);
// you can also bind *this

或者(沒有綁定參數這沒有意義 - 如果你願意,可以綁定abc ):

auto test = std::bind(&SomeClass::test_function,
                      std::placeholders::_1, std::placeholders::_2,
                      std::placeholders::_3, std::placeholders::_4);
test(this, a, b, c); // you can also pass a reference

和那樣的東西。

您將需要傳入對SomeClass::test_function將運行的對象的引用(很可能是this )。 Cppreference描述了std::bind工作原理。

另一個選擇是使SomeClass::test_function成為一個靜態成員函數,它不需要將實例傳遞給bind。

當使用std::bind到成員函數時, this指針需要特征(即它需要訪問類的實例)。 捕獲作為bind的參數或稍后在調用綁定類型時作為參數。

例如;

auto test = std::bind(&SomeClass::test_function, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
test(a, b, c);

當您使用bind捕獲指向成員函數的指針時,生成的bind對象的第一個參數必須是引用合適類型的對象的東西。 既然你結合SomeClass::test_function你需要類型的對象SomeClass將其應用到的,所以第一個參數test必須是類型的對象SomeClass或指針類型的對象SomeClass 對於初學者,請嘗試這樣調用:

test(this, b, c);

暫無
暫無

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

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