I have a class
class fobj{
public:
fobj(int i):id(i) {}
void operator()()
{
std::cout<<"Prints"<<std::endl;
}
private:
int id;
};
template<typename T>
void func(T type)
{
type();
}
If I invoke func like
Method 1:
func(fobj(1));
the message I wanted to print is printed.
I was always thinking I needed to do something like
Method 2:
fobj Iobj(1); // create an instance of the fobj class
func(Iobj); // call func by passing Iobj(which is a function object)
How does Method 1 work? I mean what exactly happens?
And how is a call made to the operator() in class fobj ?
One thing to note is that this works because your template class is taking an object by value:
because of this, it can take either an lvalue (such as an actual variable) or an rvalue (such as the temporary).
If for some reason you did want to limit
functo only taking an lvalue, you could modify the function to using pass by reference:using pass by reference does allow the side effect of the function being able to modify the object.