Eternal Learner
Eternal Learner

Reputation: 3870

How does calling this function object work?

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 ?

Upvotes: 1

Views: 202

Answers (2)

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76541

One thing to note is that this works because your template class is taking an object by value:

template<typename T>
void func(T type)   // this takes a T 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 func to only taking an lvalue, you could modify the function to using pass by reference:

template <typename T>
void func(T &type)  // this takes a T by reference
...

using pass by reference does allow the side effect of the function being able to modify the object.

Upvotes: 2

CB Bailey
CB Bailey

Reputation: 791879

In func(fobj(1)), fobj(1) creates a temporay fobj from the literal int 1. This temporary is used to initialized the function parameter type (there's an implicit copy which the compiler may elide), and in the body of the function operator() is invoked on the function object.

I think that naming the function parameter type is a bit misleading. type is the name of the T instance (in this case a fobj) that is the function parameter.

Upvotes: 2

Related Questions