This article needs additional citations for verification .(May 2017) |
A callable object, in computer programming, is any object that can be called like a function.
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.
importstd;structFoo{voidoperator()()const{std::println("Called.");}};intmain(){Fooinstance;instance();// This will output "Called." to the screen.}
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]
classMinus{publicfunction__invoke($x,$y){return$x-$y;}}$a=array(3,1,4);usort($a,newMinus());
In Python any object with a __call__()
method can be called using function-call syntax.
classFoo:def__call__(self)->None:print("Called.")instance:Foo=Foo()instance()# This will output "Called." to the screen.
Another example:
classAccumulator:def__init__(self,n:int)->None:self.n=ndef__call__(self,x:int)->int:self.n+=xreturnself.n
Callable objects are defined in Dart using the call()
method.
classWannabeFunction{call(Stringa,Stringb,Stringc)=>'$a$b$c!';}main(){varwf=newWannabeFunction();varout=wf("Hi","there,","gang");print('$out');}
In Swift, callable objects are defined using callAsFunction
. [4]
structCallableStruct{varvalue:IntfunccallAsFunction(_number:Int,scale:Int){print(scale*(number+value))}}letcallable=CallableStruct(value:100)callable(4,scale:2)callable.callAsFunction(4,scale:2)// Both function calls print 208.