Reputation: 24766
I have few question about ()
operator. Please help me to get clear idea.
()
operator (()
operator overloading).()
operator usage (in which situations that useful,convenient or suitable to use ()
operator ).Upvotes: 0
Views: 123
Reputation: 2646
The () operator is used to make what is known as a function object aka "functor"
There are some very interesting things that having a function object allows one to do including passing a function object as a parameter.
The link I am posting below is a video from a class I was taking where the professor is talking about functors. I find it very helpful. (Note: the vid also talks about class templates)
Upvotes: 1
Reputation: 385088
It's primarily used in function objects to simulate function calls.
#include <iostream>
struct Functor
{
void operator()() {
std::cout << "lol\n";
}
};
int main()
{
Functor f;
f(); // output: "lol"
}
A contrived example, yes, but this gets more complex with constructor arguments and when, say, storing this functor for use in an algorithm. It's very common in the C++ standard library.
You don't have to use it in this way; another example is simulating multi-dimensional array access:
#include <vector>
template<typename T>
struct Matrix
{
Matrix(unsigned m, unsigned n)
: m(m), n(n), vs(m*n) {}
T& operator()(unsigned i, unsigned j)
{
return vs[i + m * j];
}
private:
unsigned m;
unsigned n;
std::vector<T> vs;
};
/**
* _~
* _~ )_)_~
* )_))_))_)
* _!__!__!_
* \______t/
* ~~~~~~~~~~~~~
*/
int main()
{
const unsigned int WIDTH = 3;
const unsigned int HEIGHT = 3;
Matrix<long> m(WIDTH, HEIGHT);
m(1,1) = 42;
}
This one is useful because operator[]
may take only one parameter (though that parameter can be an initializer list, which is a workaround).
Upvotes: 5