简体   繁体   中英

Syntax error of a pointer to member function

Salutations I'm trying to use the std::sort algorithms on specials objects. I got a list to sort and a binary function which give me a comparison:

Interesting part of B.cpp

    void B::FindClosest(vector<A*> list)
        {     
          bool (B::*ptr)(A*,A*) = &B::Closer;     
          sort(list.begin(),list.end(),(this->*ptr));
          // some use of this sorted list   
        }

    bool B::Closer(A* lhs ,A* rhs)
    {
       if(Distance(this,lhs)<Distance(this,rhs))
       {
          return true;
       }
       else
       {
          return false;
       }
     }

And Bh :

  class B : public A
   public:
   void FindClosest(vector<A*>);
   bool Closer(A*,A*);

This seems pretty simple but i can't figure out why it's not working. It seems to me that i'm doing something wrong on pointer to member function but cant find out what.

Here is the error msg :

agglomerate.cpp:32: error: invalid use of non-static member function

I've tried some other way to get things to work but nothing.

I'm not bound to pointer to member function, if you got a simple / different way to do this you're welcome.

Thanks a lot,

Azhrilla

You cannot use such thing, you should use std::bind or boost::bind or lambda for this case, since sort third parameter should be callable object, that receive two objects of type T .

With std::bind it will be

using namespace std::placeholders;
sort(list.begin(), list.end(), std::bind(ptr, this, _1, _2));

This line:

bool (B::*ptr)(A*,A*) = &B::Closer;

Gets a point to the member function B. To call this function you then need a class instance to call it on (the member function needs to know which conrete instance of class data it can access etc). For example

(this->*ptr)(lhs, rhs)

Calls the member function of this. If you did

B anotherB;
bool (B::*ptr)(A*,A*) = &B::Closer;
(anotherB.*ptr)(lhs, rhs)

That would call the B::Closer function but this time using anotherB and not this (assuming this was not 'anotherB')

I'm not sure what...

 (this->*ptr)

...evaluates to?, but it is the problem

I think the problem is that you cannot give sort() the class instance and the member function pointer... you can only give it the member function pointer and so it has no class instance on which to call this function.

As ForEveR suggests, you could usde std::bind so that you can convert from a function withfour parameters, hls, rhs, class-instance, member-pointer. bind one to 'this' and one to the desired member function, so that the result is a function that just needs lhs and rhs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM