名前空間
変種
操作

C++ 名前付き要件: FunctionObject

From cppreference.com
 
 
C++ 名前付き要件
 

FunctionObject 型とは、関数呼び出し演算子の左側に使用できるオブジェクトの型です。

目次

[編集] 要件

TFunctionObject を満たすのは、

以下を考えます。

  • f は型 T または const T の値であり、
  • args は、空でもよい適切な引数リストです。

以下の式が有効である必要があります。

Expression 要件
f(args) 関数呼び出しを実行します。

[編集] 注釈

関数および関数への参照は関数オブジェクト型ではありませんが、関数からポインタへの暗黙の変換により、関数オブジェクト型が期待される場所で使用できます。

[編集] 標準ライブラリ

[編集]

異なる種類の関数オブジェクトを示します。

#include <functional>
#include <iostream>
 
void foo(int x) { std::cout << "foo(" << x << ")\n"; }
void bar(int x) { std::cout << "bar(" << x << ")\n"; }
 
int main()
{
    void(*fp)(int) = foo;
    fp(1); // calls foo using the pointer to function
 
    std::invoke(fp, 2); // all FunctionObject types are Callable
 
    auto fn = std::function(foo); // see also the rest of <functional>
    fn(3);
    fn.operator()(3); // the same effect as fn(3)
 
    struct S
    {
        void operator()(int x) const { std::cout << "S::operator(" << x << ")\n"; }
    } s;
    s(4); // calls s.operator()
    s.operator()(4); // the same as s(4)
 
    auto lam = [](int x) { std::cout << "lambda(" << x << ")\n"; };
    lam(5); // calls the lambda
    lam.operator()(5); // the same as lam(5)
 
    struct T
    {
        using FP = void (*)(int);
        operator FP() const { return bar; }
    } t;
    t(6); // t is converted to a function pointer
    static_cast<void (*)(int)>(t)(6); // the same as t(6)
    t.operator T::FP()(6); // the same as t(6) 
}

出力

foo(1)
foo(2)
foo(3)
foo(3)
S::operator(4)
S::operator(4)
lambda(5)
lambda(5)
bar(6)
bar(6)
bar(6)

[編集] 関連項目

呼び出し操作が定義されている型
(名前付き要件)
English 日本語 中文(简体) 中文(繁體)