【发布时间】:2013-09-01 14:17:59
【问题描述】:
我在代码的不同位置使用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 的类型肯定是std::function<int(int)>(foo 的类型绑定了 1 个int 参数),那么为什么bar_fun 编译失败呢?我包括了bar_fun_lvalue,因为一些谷歌搜索向我展示了rvalues used to be problematic。但这并没有解决任何问题。
它类似于this bug,但它太老了,我不认为它是相关的。
gcc 的输出并不是特别有启发性:
在 bindnew.cpp:1:0 包含的文件中: /usr/include/c++/4.7/functional:在“静态_Res”的实例化中 std::_Function_handler<_res ... _functor>::_M_invoke(const std::_Any_data&, _ArgTypes ...) [with _Res = int; _函子 = std::_Bind))(int, int)>; _ArgTypes = {int}]’:/usr/include/c++/4.7/functional:2298:6:需要来自 'std::function<_res ...>::function(_Functor, typename 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/functional:1912:40:错误:调用不匹配 '(std::_Bind))(int, int)>) (int)' /usr/include/c++/4.7/functional:1140:11:注意:候选人是: /usr/include/c++/4.7/functional: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/functional:1211:2: 注意:
模板参数扣除/替换失败: /usr/include/c++/4.7/functional:1206:35:错误:无法转换 参数传递中的“std::_No_tuple_element”到“int” /usr/include/c++/4.7/functional: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/functional:1225:2: 注意:
模板参数扣除/替换失败: /usr/include/c++/4.7/functional:1219:35:错误:无法转换 参数传递中的“std::_No_tuple_element”到“int” /usr/include/c++/4.7/functional:1239:2: 注意:模板 _Result std::_Bind<_functor ...>::operator()(_Args&& ...) volatile [with _Args = {_Args ...}; _结果 = _结果; _Functor = int (*)(int, int); _Bound_args = {int, std::_Placeholder}] /usr/include/c++/4.7/functional:1239:2: 注意:
模板参数扣除/替换失败: /usr/include/c++/4.7/functional:1233:35:错误:无法转换 参数传递中的“std::_No_tuple_element”到“int” /usr/include/c++/4.7/functional:1253:2:注意:模板 _Result std::_Bind<_functor ...>::operator()(_Args&& ...) const volatile [with _Args = { _Args ...}; _结果 = _结果; _Functor = int (*)(int, int); _Bound_args = {int, std::_Placeholder}] /usr/include/c++/4.7/functional:1253:2: 注意:模板参数扣除/替换失败: /usr/include/c++/4.7/functional:1247:35:错误:无法转换 参数传递中的“std::_No_tuple_element”到“int”
【问题讨论】:
标签: c++11