问题描述
我在用std :: function和std :: bind玩游戏时,发现一些不直观的东西,我想更好地理解它.
I was playing arround with std::function and std::bind and I noticed something unintuitive and I would like to understand it better.
例如:
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;
}
如何将 function<void(int)>
绑定到 void()的函数.然后,我可以调用f(1)并获得fun().我想了解这是如何完成的.深入了解Microsoft Visual Studio 2012的实现,这让我迷失了一大堆无法读取的宏.所以这就是为什么我在这里问这个问题.
How is it possible to bind a function<void(int)>
to a function that is void().I could then call f(1) and get fun().I would like to understand how this is done.Going inside Microsoft Visual Studio 2012's implementation of this got me lost in a sea of unreadable macros. so that is why I ask this question here.
推荐答案
如果不使用参数占位符(_1
,_2
,...),则传递给函数对象的所有参数均从将被丢弃.使用:
If you don't use argument placeholders (_1
, _2
, ...), then any arguments passed to the function object returned from std::bind
will just be discarded. With:
std::function<void(int)> f = std::bind(fun, std::placeholders::_1);
我得到了一个(长而丑陋的)错误.
I get a (long and ugly) error as expected.
对于对Standardese感兴趣的人:
For the people interested in Standardese:
§20.8.9.1.2 [func.bind.bind]
template<class F, class... BoundArgs>
*unspecified* bind(F&& f, BoundArgs&&... bound_args);
p10绑定参数v1, v2, ..., vN
的值及其对应的类型V1, V2, ..., VN
取决于从对bind
和 cv的调用派生的类型TiD
.调用包装器g
的em>-限定符 cv 如下:
p10 The values of the bound arguments v1, v2, ..., vN
and their corresponding types V1, V2, ..., VN
depend on the types TiD
derived from the call to bind
and the cv-qualifiers cv of the call wrapper g
as follows:
- 如果
TiD
是reference_wrapper<T>
,则参数是tid.get()
,其类型Vi
是T&
; - 如果
is_bind_expression<TiD>::value
的值为true
,则参数为tid(std::forward<Uj>(uj)...)
,其类型Vi
为result_of<TiD cv (Uj...)>::type
; - 如果
is_placeholder<TiD>::value
的值j
不为零,则参数为std::forward<Uj>(uj)
,其类型Vi
为Uj&&
; - 否则,该值为
tid
,其类型Vi
为TiD cv &
.
- if
TiD
isreference_wrapper<T>
, the argument istid.get()
and its typeVi
isT&
; - if the value of
is_bind_expression<TiD>::value
istrue
, the argument istid(std::forward<Uj>(uj)...)
and its typeVi
isresult_of<TiD cv (Uj...)>::type
; - if the value
j
ofis_placeholder<TiD>::value
is not zero, the argument isstd::forward<Uj>(uj)
and its typeVi
isUj&&
; - otherwise, the value is
tid
and its typeVi
isTiD cv &
.
这篇关于了解std :: function和std :: bind的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!