I'm currently studying boost threads. And I came across that the thread class has a constructor that accepts callable objects. What are callable objects?
class CallableClass { private: // Number of iterations int m_iterations; public: // Default constructor CallableClass() { m_iterations=10; } // Constructor with number of iterations CallableClass(int iterations) { m_iterations=iterations; } // Copy constructor CallableClass(const CallableClass& source) { m_iterations=source.m_iterations; } // Destructor ~CallableClass() { } // Assignment operator CallableClass& operator = (const CallableClass& source) { m_iterations=source.m_iterations; return *this; } // Static function called by thread static void StaticFunction() { for (int i=0; i < 10; i++) // Hard-coded upper limit { cout<<i<<"Do something in parallel (Static function)."<<endl; boost::this_thread::yield(); // 'yield' discussed in section 18.6 } } // Operator() called by the thread void operator () () { for (int i=0; i<m_iterations; i++) { cout<<i<<" - Do something in parallel (operator() )."<<endl; boost::this_thread::yield(); // 'yield' discussed in section 18.6 } } };
How does this become a callable object? Is it because of the operator overloaded or the constructor or something else?
In Python, a callable is a function-like object, meaning it's something that behaves like a function. Just like with a function, you can use parentheses to call a callable. Functions are callables in Python but classes are callables too!
In Python, classes, methods, and instances are callable because calling a class returns a new instance.
A function object, or functor, is any type that implements operator(). This operator is referred to as the call operator or sometimes the application operator. The C++ Standard Library uses function objects primarily as sorting criteria for containers and in algorithms.
A callable object is a data structure that behaves as both an object and a function. You can access and assign properties obj.bar , call methods obj.foo() , but also call the object directly obj() , as if it were a function.
A callable object is something that can be called like a function, with the syntax object()
or object(args)
; that is, a function pointer, or an object of a class type that overloads operator()
.
The overload of operator()
in your class makes it callable.
There are two steps here. In the C++ Standard, a "function object" is an object that can appear on the left-hand side of a parenthesized argument list, i.e, a pointer to function or an object whose type has one or more operator()
s. The term "callable object" is broader: it also includes pointers to members (which can't be called with the normal function call syntax). Callable objects are the things that can be passed to std::bind
etc. See 20.8.1 [func.def] and 20.8[function.objects]/1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With