Callable object

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.

# Python 3 Syntax
class Foo(object):
    def __call__(self):
        print("Called.")

foo_instance = Foo()
foo_instance()  # This will output "Called." to the screen.

[2]

Another example:

class Accumulator(object):
    def __init__(self, n):
        self.n = n

    def __call__(self, x):
        self.n += x
        return self.n

In Dart

To allow your Dart class to be called like a function, implement 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');
}

[3]

gollark: I've checked a bit and I know my config, YOU are wrong.
gollark: No, the site supports 2.0 fine.
gollark: HTTP/2 predates the encrypted SNI thing, and indeed the latter is not really implemented many places yet.
gollark: ```osmarks@fenrir ~/Downloads> curl -I https://osmarks.tk/HTTP/2 200 server: nginx/1.18.0date: Mon, 09 Nov 2020 21:50:42 GMTcontent-type: text/htmlcontent-length: 11144last-modified: Mon, 21 Sep 2020 17:33:13 GMTetag: "5f68e3d9-2b88"strict-transport-security: max-age=63072000; preload; includeSubDomainsreferrer-policy: strict-origin-when-cross-originaccept-ranges: bytes```
gollark: 1. It is set up and works2. Encrypted SNI is a separate (TLS) thing

References

  1. PHP Documentation on Magic Methods
  2. Bösch, Florian. "What is a "callable" in Python?". StackOverflow.com. Retrieved 24 September 2017.
  3. "A Tour of the Dart Language". www.dartlang.org. Retrieved 2019-03-25.


This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.