tags:

views:

80

answers:

2

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();
}

My Doubt is 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 ?

+2  A: 

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.

Charles Bailey
+2  A: 

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.

R Samuel Klatchko
One advantage of posting in Stack Overflow is the amazing replies :). Thanks
Eternal Learner