关于std::bind的问题

C++语言 码拜 7年前 (2017-04-16) 955次浏览
有这么个想法,
想写一组通用的调用。
使用std::bind来绑定任意函数。
然后将这些对象放进一个容器里。
最后统一顺序调用容器中的这些函数。
现在暂时想到的写法如下。

#include <functional>
#include <vector>
typedef std::function<int()> fp;  
typedef std::vector<fp> VE_FUNC;
//待绑定函数
int tests()
{
	printf("tests\n");
	return 0;
}
int tests1(int a)
{
	printf("tests1:%d\n",a);
	return 1;
}
int tests2(int a,float aa)
{
	printf("tests2:%d,%f\n",a,aa);
	return 2;
}
int tests3(int a,float aa,char* p)
{
	printf("tests3:%d,%f,%s\n",a,aa,p);
	return 3;
}
//绑定
	VE_FUNC ve_func;
	fp f = std::bind(tests);  
	ve_func.push_back(f);
	f = std::bind(tests1,12);
	ve_func.push_back(f);
	f = std::bind(tests2,12,11.11); 
	ve_func.push_back(f);
	f = std::bind(tests3,13,11.22,(char*)"1233477"); 
	ve_func.push_back(f);
//调用
	for(int i=0;i < ve_func.size(); i++)
	{
		ret = (ve_func[i])();
		printf("ret:%d\n",ret);
	}

这样做出现的实际问题,
1.容器存储类型固定了,只能存储返回值类型为int的函数。
2..无法使用占位符std::placeholders::_*,动态输入参数,这点尤其重要,假如不能使用占位符动态输入参数,那这个统一调用将毫无意义。
有哪位高手对std::bind比较熟悉的,能帮忙解答下么。

解决方案

33

1.返回类型不是必须的,你可以传个引用进去
2.容器本来就是要求元素是类型一致的,你想用占位符只能把参数表弄得一致
解决这个问题你可以想个统一调用结构,或不使用function使用其他的东西

33

假如仅仅是题主上面的三个函数,找个变通的方法就可以了。

enum E_FUN_TYPE
{
     e_FT_One,
     e_FT_Two,
     e_FT_Three
};
int tests(int a,float aa,char* p, E_FUN_TYPE eType)
{
    int nResult = -1;
    switch ( eTyp )
   {
   }
     return nResult;
}

34

建议参考:boost::bind的实现;

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于std::bind的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)