シグネチャがすべて同じであるカスタム関数と任意の関数の要素を使用して、std :: vectorオブジェクト(またはその他の標準またはカスタムコンテナタイプ)を作成したいと思います。
次のようになります。
// Define the functions and push them into a vector
std::vector<????> MyFunctions;
MyFunctions.push_back(double(int n, float f){ return (double) f / (double) n; });
MyFunctions.push_back(double(int n, float f){ return (double) sqrt((double) f) / (double) n; });
// ...
MyFunctions.push_back(double(int n, float f){ return (double) (f * f) / (double) (n + 1); });
// Create an argument list
std::vector<std::pair<int, float>> ArgumentList;
// ...
// Evaluate the functions with the given arguments
// Suppose that it is guarantied that ArgumentList and MyFunctions are in the same size
std::vector<double> Results;
for (size_t i=0; i<MyFunctions.size(); i++)
{
Results.push_back(MyFunctions.at(i)(ArgumentList.at(i).first, ArgumentList.at(i).second));
}
可能であれば、これらの関数のセットを以下のように明示的に定義したくありません。
class MyClass
{
public:
void LoadFunctions()
{
std::vector<????> MyFunctions;
MyFunctions.push_back(MyFoo_00);
MyFunctions.push_back(MyFoo_01);
MyFunctions.push_back(MyFoo_02);
// ...
MyFunctions.push_back(MyFoo_nn);
}
private:
double MyFoo_00(int n, float f) { /* ... */ }
double MyFoo_01(int n, float f) { /* ... */ }
double MyFoo_02(int n, float f) { /* ... */ }
// ...
double MyFoo_nn(int n, float f) { /* ... */ }
};
いくつかの標準ライブラリツール(を使用するなどstd::function
)を使用した実装は問題ありません。ただし、これを行うための非標準的な方法(Boost、QT、またはその他のライブラリやフレームワークを使用するなど)は推奨されません。