herzl shemuelian
herzl shemuelian

Reputation: 3498

error in :c++ template function

Hi I try build a tamplate function in vc++ like below:

template<class _Fn0,class _Fn1>   void for_each(_Fn0 _Func0,_Fn1 _Func1)
{    
    _Func0(12);
    _Func1(12);

}

when I use for _Func0/1 a global function this work propely.

void aglobal(int a)
{
    a++;
}
for_each(aglobal,aglobal);

but when I use a memeber class function I get error message.

class A
{
public:
    void aa(int a)
    {
        a++;
    }
    void bb(int b)
    {
        b++;
    }
    void cc()
    {
        for_each(&A::aa,&A::bb);
    }
};

error C2064: term does not evaluate to a function taking 1 arguments 1> see reference to function template instantiation 'void for_each(_Fn0,_Fn1)' being compiled.

How I can fix this error?

thanks herzl.

Upvotes: 1

Views: 159

Answers (2)

James McNellis
James McNellis

Reputation: 354979

A::aa and A::bb are nonstatic member functions; you are trying to call them as if they were nonmember functions.

A nonstatic member function can only be called on an instance of the object.

To fix it, you can

  1. make aa and bb static, or

  2. pass an instance of A into for_each so that it can call the functions on that instance, or

  3. use std::bind/std::tr1::bind/boost::bind to bind the member function to an instance before passing it to the function template, or

  4. write a functor that stores a pointer to the instance of A on which you want to call the member function and a pointer to the member function that you want to call; this is effectively what bind does (though bind is far more generic).

Upvotes: 9

Shuo
Shuo

Reputation: 8927

The class's member function always accept extra param "this" pointer, so you can make them static to try this.

Upvotes: 1

Related Questions