「std::function」の版間の差分

提供: C++入門
移動: 案内検索
(ページの作成:「テンプレートクラスstd::function は、関数ラッパーです。std::functionは、関数、ラムダ式、バインド式(std::bind)、[[関...」)
 
 
行52: 行52:
  
 
         // ラムダ式
 
         // ラムダ式
         std::function< void(int) > f_ramda = [=](int i) { print_number(i); };
+
         std::function< void(int) > f_lambda = [=](int i) { print_number(i); };
         f_ramda(6);
+
         f_lambda(6);
  
 
         // バインド
 
         // バインド

2014年8月27日 (水) 19:36時点における最新版

テンプレートクラスstd::function は、関数ラッパーです。std::functionは、関数、ラムダ式、バインド式(std::bind)、関数オブジェクトを格納、コピー、呼び出しができます。

読み方

std::function
えすてぃーでぃー ふぁんくしょん

概要

C++には、複数の種類の関数が存在しています。

std::functionを使用して、これらの種類の関数を呼び出すことができます。

std::functionの使用例 std_function1.cpp

ソースコード std_function1.cpp

/*
 * std_function1.cpp
 * Copyright (C) 2014 kaoru <kaoru@bsd>
 */
#include <iostream>
#include <functional>
using namespace std;
 
struct Foo {
        Foo(const int n) : i_(n) {}
        void print_add(const int n) const { std::cout << i_ + n<< std::endl; }
        int i_;
};
 
struct PrintFunctor {
        // 引数を表示するだけの関数オブジェクト
        void operator()(int i) {
                std::cout << i << std::endl;
        }
};
 
void
print_number(const int i)
{
        std::cout << i << std::endl;
}
 
int
main(int argc, char const* argv[])
{
        // 普通の関数
        std::function< void(int) > f_func = print_number;
        f_func(3);
 
        // ラムダ式
        std::function< void(int) > f_lambda = [=](int i) { print_number(i); };
        f_lambda(6);
 
        // バインド
        std::function< void() > f_bind = std::bind(print_number, 9);
        f_bind();
 
        // クラスのメンバ関数
        std::function< void(const Foo&, int) > f_member = &Foo::print_add;
        Foo foo (1);
        f_member(foo, 3);       // 1+3 = 4
 
        // 関数オブジェクト
        std::function< void(int) > f_func_obj = PrintFunctor();
        f_func_obj(11);
 
        return 0;
}

コンパイル

c++ -std=c++11  std_function1.cpp -o std_function1

実行例

% ./std_function1
3
6
9
4
11

関連項目