Przejdź do głównej zawartości

C++ named requirements: FunctionObject

A FunctionObject type is the type of an object that can be used on the left of the function call operator.

Requirements

The type T satisfies FunctionObject if

Given

  • f, a value of type T or const T
  • args, suitable argument list, which may be empty

The following expressions must be valid:

pubExpressionRequirements
pubf(args)performs a function call

Notes

Functions and references to functions are not function object types, but can be used where function object types are expected due to function-to-pointer implicit conversion.

Standard library

Example

demonstrates different types of function objects

#include <iostream>

void foo(int x) { std::cout << "foo(" << x << ")\n"; }

int main()
{
void(*fp)(int) = foo;
fp(1); // calls foo using the pointer to function

struct S {
void operator()(int x) const { std::cout << "S::operator(" << x << ")\n"; }
} s;
s(2); // calls s.operator()
s.operator()(3); // the same

auto lam = [](int x) { std::cout << "lambda(" << x << ")\n"; };
lam(4); // calls the lambda
lam.operator()(5); // the same

struct T {
static void bar(int x) { std::cout << "T::bar(" << x << ")\n"; }
using FP = void (*)(int);
operator FP() const { return bar; }
} t;
t(6); // t is converted to a function pointer
static_cast<void (*)(int)>(t)(7); // the same
}
Result
foo(1)
S::operator(2)
S::operator(3)
lambda(4)
lambda(5)
T::bar(6)
T::bar(7)

C++ named requirements: FunctionObject

A FunctionObject type is the type of an object that can be used on the left of the function call operator.

Requirements

The type T satisfies FunctionObject if

Given

  • f, a value of type T or const T
  • args, suitable argument list, which may be empty

The following expressions must be valid:

pubExpressionRequirements
pubf(args)performs a function call

Notes

Functions and references to functions are not function object types, but can be used where function object types are expected due to function-to-pointer implicit conversion.

Standard library

Example

demonstrates different types of function objects

#include <iostream>

void foo(int x) { std::cout << "foo(" << x << ")\n"; }

int main()
{
void(*fp)(int) = foo;
fp(1); // calls foo using the pointer to function

struct S {
void operator()(int x) const { std::cout << "S::operator(" << x << ")\n"; }
} s;
s(2); // calls s.operator()
s.operator()(3); // the same

auto lam = [](int x) { std::cout << "lambda(" << x << ")\n"; };
lam(4); // calls the lambda
lam.operator()(5); // the same

struct T {
static void bar(int x) { std::cout << "T::bar(" << x << ")\n"; }
using FP = void (*)(int);
operator FP() const { return bar; }
} t;
t(6); // t is converted to a function pointer
static_cast<void (*)(int)>(t)(7); // the same
}
Result
foo(1)
S::operator(2)
S::operator(3)
lambda(4)
lambda(5)
T::bar(6)
T::bar(7)