2017-09-26 93 views
0

我需要將一個參數綁定到類成員函數。 事情是這樣的:std ::將參數綁定到沒有對象的成員函數

#include <functional> 
#include <iostream> 

struct test 
{ 
    void func(int a, int b) 
    { 
     std::cout << a << " " << b << std::endl; 
    } 
}; 

int main(int argc, char** argv) 
{ 
    typedef void (test::*TFunc)(int); 
    TFunc func = std::bind(&test::func, 1, std::placeholders::_1); 
} 

但在這種情況下,我有編譯錯誤

error: static assertion failed: Wrong number of arguments for pointer-to 
-member 
+1

您可能不應該期望'std :: bind'生成的對象可以轉換爲普通成員函數指針... – Quentin

+0

如果您正在尋找一種基本上在類定義之外定義成員函數的方法,那麼這是無法完成的。您只能向該類添加重載或定義一個自由函數。 –

回答

4

std::bind不會產生一個成員函數指針,但它可以產生一個std::function對象,您可以在以後使用:

::std::function< void (test *, int)> func = std::bind(&test::func, std::placeholders::_1, 1, std::placeholders::_2); 
test t{}; 
func(&t, 2); 
+0

感謝您的回答,但您的決定與我的要求略有不同 – tenta4

+0

@ tenta4 std :: bind的返回類型始終是(某些)類類型的對象。沒有從指針到成員函數的轉換。有一件事情是沒有任何限制的'int'去。 – Caleth

相關問題