我正在玩std :: function和std :: bind,我注意到一些不直观的东西,我想更好地了解它.
例如:
void fun()
{
}
void hun(std::string)
{
}
int main()
{
function<void(int)> g = &fun; //This fails as it should in my understanding.
function<void(int)> f = std::bind(fun); //This works for reasons unkNown to me
function<void(int,std::string)> h = std::bind(hun); //this doesn't work
return 0;
}
如何绑定函数< void(int)>到一个void()函数.
我可以调用f(1)并获得乐趣().
我想了解如何做到这一点.
进入Microsoft Visual Studio 2012的这个实现让我失去了一大堆不可读的宏.所以我在这里问这个问题.
解决方法
如果不使用参数占位符(_1,_2,…),则传递给从std :: bind返回的函数对象的任何参数都将被丢弃.附:
std::function<void(int)> f = std::bind(fun,std::placeholders::_1);
我按预期得到一个(长而丑)的错误.
对于对Standardese感兴趣的人:
§20.8.9.1.2[func.bind.bind]
template<class F,class... BoundArgs> *unspecified* bind(F&& f,BoundArgs&&... bound_args);
p3 Returns: A forwarding call wrapper
gwith a weak result type (20.8.2). The effect ofg(u1,u2,...,uM)shall beINVOKE(fd,v1,v2,vN,result_of<FD cv (V1,V2,VN)>::type),where cv represents the cv-qualifiers ofgand the values and types of the bound argumentsv1,vNare determined as specified below.p10 The values of the bound arguments
v1,vNand their corresponding typesV1,VNdepend on the typesTiDderived from the call tobindand the cv-qualifiers cv of the call wrappergas follows:
- if
TiDisreference_wrapper<T>,the argument istid.get()and its typeViisT&;- if the value of
is_bind_expression<TiD>::valueistrue,the argument istid(std::forward<Uj>(uj)...)and its typeViisresult_of<TiD cv (Uj...)>::type;- if the value
jofis_placeholder<TiD>::valueis not zero,the argument isstd::forward<Uj>(uj)and its typeViisUj&&;- otherwise,the value is
tidand its typeViisTiD cv &.