C++ operator() (xxx, yyy) みたいなやつの使い方
参照したページ
https://en.cppreference.com/w/cpp/language/operators
- operator()を構造体内に定義する。複数でも可(オーバーロード可)
- 構造体を初期化する
- 初期化した構造体を関数のように使う。
上記のようにすると、下記コードのdouble a, b; の初期化を関数の実行前に実行できてすっきりする?
コード
#include <iostream>
struct Linear
{
double a, b;
double operator() (double x) const
{
return a * x + b;
}
double operator() (double x, double y) const
{
return a * x + y + b;
}
};
int main()
{
Linear f{2, 1};
Linear g{-1, 0};
double f_0 = f(0);
double f_1 = f(1);
double f_0_1 = f(0, 1);
double f_1_3 = f(1, 3);
// double f_1_3_3 = f(1, 3, 3);
// error: no match for call to ‘(Linear) (int, int, int)’
// Linearにoperatorとして定義されていない関数型は実行できない
double g_0 = g(0);
double g_1 = g(1);
std::cout << "f_0: " << f_0 << std::endl;
std::cout << "f_1: " << f_1 << std::endl;
std::cout << "f_0_1: " << f_0_1 << std::endl;
std::cout << "f_1_3: " << f_1_3 << std::endl;
std::cout << "g_0: " << g_0 << std::endl;
std::cout << "g_1: " << g_1 << std::endl;
return 0;
}
実行結果
(base) mozaki@yoshitsune:~/004_HDD/001_CODE/101_CPLUS_STUDY/Operator$ ./a.out
f_0: 1
f_1: 3
f_0_1: 2
f_1_3: 6
g_0: 0
g_1: -1
(base) mozaki@yoshitsune:~/004_HDD/001_CODE/101_CPLUS_STUDY/Operator$