0
0

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 1 year has passed since last update.

std::functionを使った関数の利用

Posted at

std::functionとは

あらゆる関数ポインタ、関数オブジェクト、メンバ関数ポインタ、メンバ変数ポインタを保持できるテンプレートクラスです。これを使うことで柔軟で汎用的なコードを書くことが出来ます。

・functionの作り方

main.h
#include<functional>
class Input;

class Function
{
    //Updata関数で実行される関数を格納するfunction
    //引数なし
    std::function<void(void)>update_;
    //引数あり
    std::function<void(Input&)>update_;

    
    //functionと結び付けるupdate関数
    void NormalUpdate(void);
    void NormalUpdate(Input& input);
}

・functionと関数の結びつけ方

Function.cpp
void Function::Init(void)
{
    //std::bindを利用して関数とクラスのインスタンス(this)を
    //結び付けている。
    update_ = std::bind(&Function::NormalUpdate,this);

    //ラムダ式を利用して関数を結び付けている。
    update_ = [&](Input& input) 
    {
		NormalUpdate(input);
	};
}

・関数オブジェクトの実行の仕方

Function.cpp
void Function::Update(Input& input)
{
    //引数なしfunctionの実行
    update_();

    //引数ありfunctionの実行
    update_(input);
}

update_に結びついている関数を変更すれば、Update関数の中身を変更しなくともUpdateの動作を変更することができ、コードの柔軟性が向上します。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?