我在使用时遇到很多麻烦std::bind
在我的代码的各个地方。有时它有效,有时则无效,所以我认为我正在做一些根本错误的事情。
据我了解,以下基本用法std::bind
应该可以正常工作:
#include <functional>
int foo(int a, int b){ return a+b; }
int main(){
using namespace std::placeholders;
// works
auto bar_auto=std::bind(foo,1,_2);
// compile error
std::function<int(int)> bar_fun=std::bind(foo,1,_2);
int quux=1;
// compile error
std::function<int(int)> bar_fun_lvalue=std::bind(foo,quux,_2);
}
肯定是类型bar_auto
is std::function<int(int)>
(类型foo
with 1 int
参数绑定),那么为什么bar_fun
编译失败?包括我bar_fun_lvalue
因为一些谷歌搜索告诉我右值曾经是有问题的 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=35569。但这并没有解决任何问题。
它类似于this bug http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52612,但那太旧了,我不认为它是相关的。
gcc 的输出并不是特别有启发性:
在bindnew.cpp:1:0 包含的文件中:
/usr/include/c++/4.7/function: 在‘static _Res 的实例化中
std::_Function_handler<_res ... _functor>::_M_invoke(const
std::_Any_data&, _ArgTypes ...) [with _Res = int; _函子 =
std::_Bind))(int, int)>;; _Arg类型 =
{int}]’: /usr/include/c++/4.7/function:2298:6: 需要
‘std::function<_res ...>::function(_Functor, 类型名
std::enable_if::value),
std::function<_res ...>::_Useless>::type) [with _Functor =
std::_Bind))(int, int)>;; _Res = int;
_ArgTypes = {int};类型名 std::enable_if::value), std::function<_res ...>::_Useless>::type = std::function::_Useless]’
bindnew.cpp:15:52:此处需要
/usr/include/c++/4.7/function:1912:40: 错误: 与调用不匹配
‘(std::_Bind))(int, int)>) (int)’
/usr/include/c++/4.7/function:1140:11:注意:候选者是:
/usr/include/c++/4.7/function:1211:2:注意:模板 _Result std::_Bind<_functor ...>::operator()(_Args&& ...) [with _Args = {_Args . ..}; _结果=
_结果; _Functor = int (*)(int, int); _Bound_args = {int, std::_Placeholder}] /usr/include/c++/4.7/function:1211:2:注意:
模板参数推导/替换失败:
/usr/include/c++/4.7/function:1206:35: 错误:无法转换
参数传递中的‘std::_No_tuple_element’到‘int’
/usr/include/c++/4.7/function:1225:2: 注意:模板 _Result std::_Bind<_functor ...>::operator()(_Args&& ...) const [with _Args = {_Args ...};
_结果 = _结果; _Functor = int (*)(int, int); _Bound_args = {int, std::_Placeholder}] /usr/include/c++/4.7/function:1225:2:注意:
模板参数推导/替换失败:
/usr/include/c++/4.7/function:1219:35: 错误:无法转换
参数传递中的‘std::_No_tuple_element’到‘int’
/usr/include/c++/4.7/function:1239:2:注意:模板 _Result std::_Bind<_functor ...>::operator()(_Args&& ...) 易失性 [with _Args = {_Args ...};
_结果 = _结果; _Functor = int (*)(int, int); _Bound_args = {int, std::_Placeholder}] /usr/include/c++/4.7/function:1239:2:注意:
模板参数推导/替换失败:
/usr/include/c++/4.7/function:1233:35: 错误:无法转换
参数传递中的‘std::_No_tuple_element’到‘int’
/usr/include/c++/4.7/function:1253:2:注意:模板 _Result std::_Bind<_functor ...>::operator()(_Args&& ...) const 易失性 [with _Args = { _Args
...}; _结果 = _结果; _Functor = int (*)(int, int); _Bound_args =
{int,std::_Placeholder}] /usr/include/c++/4.7/function:1253:2:
注意:模板参数推导/替换失败:
/usr/include/c++/4.7/function:1247:35: 错误:无法转换
参数传递中的‘std::_No_tuple_element’到‘int’