Home > Backend Development > C++ > body text

When to Choose: std::bind vs. Lambdas in C 0x?

Mary-Kate Olsen
Release: 2024-10-30 15:21:12
Original
972 people have browsed it

When to Choose: std::bind vs. Lambdas in C  0x?

Compare and Contrast: std::bind and Lambdas in C 0x

In C 0x, programmers are faced with two options for capturing a function: std::bind and lambdas. While both serve distinct purposes, they overlap in some applications. Let's delve into the strengths and limitations of each approach, taking an example of intersecting functionality.

Consider the task of creating a dice-rolling function. Using lambda, we can express this as:

<code class="cpp">auto dice = [&]() { return distribution(engine); };</code>
Copy after login

Alternatively, using std::bind, we can write:

<code class="cpp">auto dice = bind(distribution, engine);</code>
Copy after login

Monomorphic vs. Polymorphic

One fundamental distinction lies in their type behavior. Lambdas are monomorphic, meaning they have fixed argument types determined at compile time. This constraint limits the flexibility of lambdas compared to their bind counterparts.

For instance, consider a function that prints two arguments:

<code class="cpp">auto f = [](auto a, auto b) { cout << a << ' ' << b; }
Copy after login

Using this lambda with different parameter types will result in a compiler error. In contrast, std::bind allows for polymorphic behavior, enabling the function to be bound to arguments of varying types:

<code class="cpp">struct foo {
  template <typename A, typename B>
  void operator()(A a, B b) {
    cout << a << ' ' << b;
  }
};

auto f = bind(foo(), _1, _2);</code>
Copy after login

By deferring type deduction until the function is invoked, std::bind offers greater flexibility for handling diverse input types.

The above is the detailed content of When to Choose: std::bind vs. Lambdas in C 0x?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!