8
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++ラムダ式でクロージャ(ぽいもの)

Posted at

C++14で追加された汎用ラムダキャプチャ構文(ついでにジェネリックラムダ式も)を利用。

auto make_counter = [](auto init_val) {
  return [count = init_val]() mutable {
    return count++;
  };
};

auto c1 = make_counter(1);       // int型/初期値1
auto c2 = make_counter(3.14);    // double型/初期値3.14
std::cout << c1() << std::endl;  // 1
std::cout << c2() << std::endl;  // 3.14
std::cout << c1() << std::endl;  // 2
std::cout << c2() << std::endl;  // 4.14

Inspired by

8
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?