为什么不建议使用bind()? [英] Why should bind() be deprecated?

查看:898
本文介绍了为什么不建议使用bind()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读有关删除该标准中一些不推荐使用,旧的和未使用的部分的C ++ 17提案(

Reading the proposal for C++17 about removing some deprecated, old and unused parts of the standard (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4190.htm) i find section D.9 a bit strange:

D.9活页夹" [depr.lib.binders]

D.9 "Binders" [depr.lib.binders]

这定义了bind1st()/bind2nd(),它们已被bind()严格取代. (将来,我会争辩说,bind()本身已被lambda取代. 尤其是通用lambda,因此不建议使用bind(),但是 不是此提案的一部分.)

This defines bind1st()/bind2nd(), which were strictly superseded by bind(). (In the future, I'll argue that bind() itself has been superseded by lambdas and especially generic lambdas, so bind() should be deprecated, but that isn't part of this proposal.)

我没有得到关于bind()本身被lambda取代的评论.

What I don't get is the comment about bind() itself being superseded by lambdas.

如果我有课:

class A
{
  public:
    void f(int a){}
    void f(int a, int b){}
}

我想将指向A::f的函数指针传递给某个函数someFunction,以便该函数可以在从A实例化的对象上调用它,我声明了someFunction:

And I want to pass a function pointer to A::f to some function, someFunction, so that this function can call it on an object instantiated from A, I declare someFunction:

void someFunction(const std::function<void(int, int)>&);

并命名为:

A a;
someFunction(std::bind(static_cast<void (A::*)(int, int)> (&A::f),
                       std::ref(a), 
                       std::placeholders::_1,
                       std::placeholders::_2));

如何使用Lambda实现相同的目的?真的没有bind()能做的事,而用lambda不能做到吗?

How do I achieve the same thing using a lambda? Is there really nothing that bind() can do, which cannot be done with a lambda?

推荐答案

您如何做?与带有std::refplaceholders_的绑定示例相比,非常简单,也不太深奥(我的观点).

How do you do it? Very straight forward and less esoteric (my opinion) than the bind example with std::ref and placeholders_.

#include <iostream>
#include <functional>

class A
{
public:
   void f(int a) {}
   void f(int a, int b) { std::cout << a + b << '\n';}
};

void someFunction(const std::function<void(int, int)>& f)
{
   f(1, 2);
}

int main()
{
   A a;
   someFunction([&] (int x, int y) { a.f(x, y); });
   return 0;
}

这篇关于为什么不建议使用bind()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆