LoginSignup
54
57

More than 5 years have passed since last update.

std::functionの使い方 in C++

Posted at

機能

C++に存在する複数の種類の関数をラップして同じように扱う
C++にある関数の種類

  • 関数
  • ラムダ式
  • 関数オブジェクト
  • クラスのメンバ関数

ラムダ式の使い方

[キャプチャー](引数)->返り値の型{関数の内容}(実行時の引数);

キャプチャーには基本的に[=]か[&]が入る
=はスコープ外の変数を利用する時コピーするという意味
&はスコープ外の変数を利用する時参照するという意味
[]{}();のように引数や返り値を省略することもできる

使い方

std::function< 戻り値の方(引数の型) > object = 関数or ラムダ式 or 関数オブイェクト orクラスのメンバ関数;
object(引数);で利用できる

サンプル


/*
 * 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;
}
54
57
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
54
57