David Hall
David Hall

Reputation: 535

Define predicate within class

I have a class with a method which I would also like to be able to use as a predicate.

class MyClass {
  bool ParticleHasAncestor(const Particle &particle, int id) const;

  class AncestorPredicate {
    int mId;
   public:
    AncestorPredicate(int idCode) : mId(idCode) { }
    bool operator()(const Particle &particle) const { return ParticleHasAncestor(particle, mId); }
  };
};

However, the compiler complains about not being able to use ParticleHasAncestor() without an instance of MyClass. Do I need to use a friend class? Or is there a better solution to this?

I am not using C++11, so cannot use lambda functions.

Update: ParticleHasAncestor() cannot be made static since it uses members of MyClass.

Upvotes: 3

Views: 925

Answers (2)

Daniele Pallastrelli
Daniele Pallastrelli

Reputation: 2552

Unlike Java, in C++ an inner class does not own a pointer to the outer class.

MyClass::AncestorPredicate, does not have an instance of MyClass, and you cannot invoke a non-static method of MyClass without a pointer to an object of that class.

You have two options:

First. Make MyClass::ParticleHasAncestor a static method of MyClass:

class MyClass {
    static bool ParticleHasAncestor(const Particle &particle, int id);

    class AncestorPredicate {
        int mId;
    public:
        AncestorPredicate(int idCode) : mId(idCode) { }
        bool operator()(const Particle &particle) const 
        { 
            return MyClass::ParticleHasAncestor(particle, mId);
        }
    };
};

Second. Create an instance of MyClass and pass a pointer to AncestorPredicate, so that you can invoke ParticleHasAncestor on that object:

class MyClass {
    bool ParticleHasAncestor(const Particle &particle, int id) const;

    class AncestorPredicate {
        int mId;
        const MyClass* obj;
    public:
        AncestorPredicate(int idCode, const MyClass* _obj) : mId(idCode), obj( _obj ) { }
        bool operator()(const Particle &particle) const 
        { 
            return obj -> ParticleHasAncestor(particle, mId);
        }
    };
};

Upvotes: 0

cpp
cpp

Reputation: 3801

Make this predicate a static method. But it cannot be const then.

Upvotes: 5

Related Questions