Question

I have a class like this:

    class AI
    {
    private:
        struct Comparator
        {
            bool operator()(const Town* lfs, const Town* rhs)
            {
                return GetHeuristicCost(lfs) > GetHeuristicCost(rhs);
            }
        };
int GetHeuristicCost(const Town* town);
    // constructor and variables
    };

GetHeuristicCost returns the heuristic from the town parameter to the exit of the path.

What I am trying to do is overload the bool operator for a priority queue but it gives me the error

a nonstatic member reference must be relative to a specific object

I know why it is giving me this error but what I don't know is how to use a nonstatic function inside the Comparator struct.

  1. GetHeuristicCost must be nonstatic
  2. I tried moving GetHeuristicCost inside the Town class to no avail
  3. I need to overload the operator with a struct because I need to use two different bool overloadings on the () for two different circumstances but with the same parameters (two Towns). In other words I need the struct so I can't do this:

    bool operator()(const Town* lfs, const Town* rhs) { return GetHeuristicCost(lfs) > GetHeuristicCost(rhs); }

Basically I plan on having two structs like this:

struct Comparator1
{
    bool operator()(const Town* lfs, const Town* rhs)
    {
        return GetHeuristicCost(lfs) > GetHeuristicCost(rhs);
    }
};

struct Comparator2
{
    bool operator()(const Town* lfs, const Town* rhs)
    {
        return GetHeuristicCost(lfs) + GetTotalCost (lfs, rhs) > GetHeuristicCost(rhs) + GetTotalCost (lfs, rhs);
    }
};
Was it helpful?

Solution

You need to construct instances of the Comparator nested class with a pointer/reference to their "outer" class instance.

class AI
{
private:
    struct Comparator
    {
        const AI &outer;

        Comparator(const AI &o):outer(o){}

        bool operator()(const Town* lfs, const Town* rhs)const
        {
            return outer.GetHeuristicCost(lfs) > outer.GetHeuristicCost(rhs);
        }
    };

    int GetHeuristicCost(const Town* town)const;
};

// how to use in code:
AI::Comparator comp(*this);
priority_queue<Town*, vector<Town*>, AI::Comparator> priorityQueue(comp);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top