2017-09-26 95 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

相关问题