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.

C++ operator() (xxx, yyy) みたいなやつの使い方

Last updated at Posted at 2024-01-15

C++ operator() (xxx, yyy) みたいなやつの使い方

参照したページ
https://en.cppreference.com/w/cpp/language/operators

  1. operator()を構造体内に定義する。複数でも可(オーバーロード可)
  2. 構造体を初期化する
  3. 初期化した構造体を関数のように使う。

上記のようにすると、下記コードの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$
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?