やあ
関数の配列ってどうやるんだろーって調べながら書いてみた。
間違ってるところとか、もっといい書き方あれば教えてください。
メンバ関数の配列
FuncArray.h
#pragma once #include <vector> class FuncArray { public: FuncArray(); using PtoIntNoParamFunc = int (FuncArray::*) () const; // typedef int (FuncArray::*PtoIntNoParamFunc) (); using PtoVoidOneIntParamFunc = void (FuncArray::*) (const int&); // typedef void (FuncArray::*PtoVoidOneIntParamFunc) (const int&); void ShowSpecs() const; std::vector<PtoVoidOneIntParamFunc> GetAddFuncs() { return AddFuncs; } protected: int A; int GetA() const; void AddA(const int& In); int B; int GetB() const; void AddB(const int& In); int C; int GetC() const; void AddC(const int& In); std::vector<PtoIntNoParamFunc> GetFuncs = { &FuncArray::GetA, &FuncArray::GetB, &FuncArray::GetC }; std::vector<PtoVoidOneIntParamFunc> AddFuncs = { &FuncArray::AddA, &FuncArray::AddB, &FuncArray::AddC }; };
FuncArray.cpp
#include "FuncArray.h" #include <iostream> FuncArray::FuncArray() { A = 10; B = 4; C = 111; } int FuncArray::GetA() const { return A; } int FuncArray::GetB() const { return B; } int FuncArray::GetC() const { return C; } void FuncArray::AddA(const int& In) { A += In; } void FuncArray::AddB(const int& In) { B += In; } void FuncArray::AddC(const int& In) { C += In; } void FuncArray::ShowSpecs() const { for (auto&& Func : GetFuncs) { std::cout << (this->*Func)() << std::endl; } }
Main.cpp
#include "FuncArray.h" int main() { FuncArray* FuncArrayTest = new FuncArray(); int Idx = 0; for (auto&& func : FuncArrayTest->GetAddFuncs()) { (FuncArrayTest->*func)(Idx); ++Idx; } FuncArrayTest->ShowSpecs(); }
グローバル関数の配列
Main.cpp
using PtoFuncArrayTest = void(*) (); void FuncA() { std::cout << "FuncA()" << std::endl; } void FuncB() { std::cout << "FuncB()" << std::endl; } void FuncC() { std::cout << "FuncC()" << std::endl; } int main() { PtoFuncArrayTest funcs[] = { FuncA, FuncB, FuncC }; for (auto&& func : funcs) { func(); } return 0; }