概要
C++で関数呼び出し演算子operator()をオーバーロードすることの役割は、オブジェクトを関数のように呼び出せるようにすることです。operator()をオーバーロードすることで、カスタム関数オブジェクト(ファンクタ)を作成し、オブジェクトにパラメータを渡して結果を返すことができます。
使用場面
関数オブジェクト(ファンクタ)
operator()
をオーバーロードすることで、独自の関数オブジェクトを定義し、これらのオブジェクトを関数のように呼び出すことができます。
/*
Functor関数オブジェクト
*/
class Adder
{
public:
// 関数オブジェクト
int operator()(int a, int b) const
{
return a + b;
}
};
int main()
{
Adder add;
std::cout << add(3, 4) << std::endl; // 7
return 0;
}
ラムダ式
ラムダ式も本質的には呼び出し可能なオブジェクトであり、関数オブジェクトとして使用でき、アルゴリズムやSTLコンテナのメンバー関数に渡すことができます。
/*
ラムダ式
*/
int main()
{
//
auto add = [](int a, int b)
{
return a + b;
};
std::cout << add(3, 4) << std::endl; // 7
return 0;
}
特定の機能を持つ呼び出し可能オブジェクトの実装
operator()
をオーバーロードすることで、オブジェクトの動作を定義し、オブジェクトを呼び出して特定の操作を実行できます。この機能は、ストラテジーパターン、イベント処理、コールバック関数などのシナリオで非常に役立ちます。
/*
特定の機能を持つ呼び出し可能オブジェクトの実装
*/
class GreaterThan
{
int threshold;
public:
explicit GreaterThan(int threshold) : threshold(threshold)
{
}
bool operator()(int num) const
{
return num > threshold;
}
};
class LessThan
{
private:
int threshold_{ 0 };
public:
explicit LessThan(int threshold) : threshold_(threshold)
{
};
bool operator()(int target) const
{
return target < threshold_;
};
};
int main()
{
std::vector<int> numbers = { 0,1, 2, 3, 4, 5 };
auto count = std::count_if(numbers.begin(), numbers.end(), GreaterThan(3));
std::cout << "Numbers greater than 3: " << count << std::endl; // 2
count = std::count_if(numbers.begin(), numbers.end(), LessThan(3));
std::cout << "Numbers less than 3: " << count << std::endl; // 3
return 0;
}