加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 了解std :: function和std :: bind

发布时间:2020-12-16 03:16:30 所属栏目:百科 来源:网络整理
导读:我正在玩std :: function和std :: bind,我注意到一些不直观的东西,我想更好地了解它. 例如: void fun(){}void hun(std::string) { }int main(){ functionvoid(int) g = fun; //This fails as it should in my understanding. functionvoid(int) f = std::bi
我正在玩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 g with a weak result type (20.8.2). The effect of g(u1,u2,...,uM) shall be INVOKE(fd,v1,v2,vN,result_of<FD cv (V1,V2,VN)>::type),where cv represents the cv-qualifiers of g and the values and types of the bound arguments v1,vN are determined as specified below.

p10 The values of the bound arguments v1,vN and their corresponding types V1,VN depend on the types TiD derived from the call to bind and the cv-qualifiers cv of the call wrapper g as follows:

  • if TiD is reference_wrapper<T>,the argument is tid.get() and its type Vi is T&;
  • if the value of is_bind_expression<TiD>::value is true,the argument is tid(std::forward<Uj>(uj)...) and its type Vi is result_of<TiD cv (Uj...)>::type;
  • if the value j of is_placeholder<TiD>::value is not zero,the argument is std::forward<Uj>(uj) and its type Vi is Uj&&;
  • otherwise,the value is tid and its type Vi is TiD cv &.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读