Английская Википедия:Callable object
Материал из Онлайн справочника
Перейти к навигацииПерейти к поиску
Шаблон:See also Шаблон:More citations needed
A callable object, in computer programming, is any object that can be called like a function.
In different languages
In C++
- pointer to function;
- pointer to member function;
- functor;
- lambda expression.
std::function
is a template class that can hold any callable object that matches its signature.
In C++, any class that overloads the function call operator operator()
may be called using function-call syntax.
#include <iostream>
struct Foo
{
void operator()() const
{
std::cout << "Called.";
}
};
int main()
{
Foo foo_instance;
foo_instance(); // This will output "Called." to the screen.
}
In C#
In PHP
PHP 5.3+ has first-class functions that can be used e.g. as parameter to the usort()
function:
$a = array(3, 1, 4);
usort($a, function ($x, $y) { return $x - $y; });
It is also possible in PHP 5.3+ to make objects invokable by adding a magic __invoke()
method to their class:[1]
class Minus
{
public function __invoke($x, $y) { return $x - $y; }
}
$a = array(3, 1, 4);
usort($a, new Minus());
In Python
In Python any object with a __call__()
method can be called using function-call syntax.
class Foo:
def __call__(self):
print("Called.")
foo_instance = Foo()
foo_instance() # This will output "Called." to the screen.
Another example:
class Accumulator:
def __init__(self, n):
self.n = n
def __call__(self, x):
self.n += x
return self.n
In Dart
Callable objects are defined in Dart using the call()
method.
class WannabeFunction {
call(String a, String b, String c) => '$a $b $c!';
}
main() {
var wf = new WannabeFunction();
var out = wf("Hi","there,","gang");
print('$out');
}
In Swift
In Swift, callable objects are defined using callAsFunction
.[4]
struct CallableStruct {
var value: Int
func callAsFunction(_ number: Int, scale: Int) {
print(scale * (number + value))
}
}
let callable = CallableStruct(value: 100)
callable(4, scale: 2)
callable.callAsFunction(4, scale: 2)
// Both function calls print 208.
References
External links
Категории:
- Английская Википедия
- Articles with example C++ code
- Articles with example C Sharp code
- Articles with example PHP code
- Articles with example Python (programming language) code
- Articles with example Swift code
- Object (computer science)
- Subroutines
- Страницы, где используется шаблон "Навигационная таблица/Телепорт"
- Страницы с телепортом
- Википедия
- Статья из Википедии
- Статья из Английской Википедии