How to call a () operator in a struct

How to call a () operator in a struct

I have a node graph with the following definition:

class Node {
public:
    // Joint configuration associated with the node
    Eigen::VectorXd q;
    std::shared_ptr<Node> parent;

    // Dictionary of neighboring nodes and their distances
    std::unordered_map<std::shared_ptr<Node>, double> neighbors;

    // Constructor
    Node(const Eigen::VectorXd& q, std::shared_ptr<Node> parent = nullptr) {
        this->q = q;
        this->parent = parent;
    }

    struct Hash {
        std::size_t operator()(const std::shared_ptr<Node>& node) const {
            return std::hash<std::string>()(std::string(reinterpret_cast<const char*>(node->q.data()), node->q.size() * sizeof(double)));
        }
    };
    
    struct Equal {
        bool operator()(const std::shared_ptr<Node>& a, const std::shared_ptr<Node>& b) const {
            return a->q == b->q;
        }
    };
    
    struct Compare {
        bool operator()(const std::shared_ptr<Node>& a, const std::shared_ptr<Node>& b) const {
            return std::lexicographical_compare(a->q.begin(), a->q.end(), b->q.begin(), b->q.end());
        }
    };
};

And i am creating a edge graph that needs to access the Node::Hash operator

class Edge {
public:
    std::shared_ptr<Node> node_a;
    std::shared_ptr<Node> node_b;
    double cost;

    // Constructor
    Edge(std::shared_ptr<Node> node_a, std::shared_ptr<Node> node_b, double cost = 0.0) 
    {
        this->node_a = node_a;
        this->node_b = node_b;
        this->cost = cost;
    }

    // Return a string representation of the edge.
    std::string to_string() const
    {
        return "Edge(node_a=(" + this->node_a->to_string() + "), node_b=(" + this->node_b->to_string()
                + "), cost=" + std::to_string(this->cost) + ")";
    }

    struct Hash {
        std::size_t operator()(const std::shared_ptr<Edge>& edge) const {
            return 0;
            //return Node::Hash::operator(edge->node_a) ^ (Node::Hash::operator(edge->node_b) << 1); 
        }
    };
    
    struct Equal {
        bool operator()(const std::shared_ptr<Edge>& a, const std::shared_ptr<Edge>& b) const {
            return a->node_a == b->node_a && a->node_b == b->node_b;
        }
    };
};

However, the syntax return Node::Hash::operator(edge->node_a) ^ (Node::Hash::operator(edge->node_b) << 1); does not seem to work. How do i actually call the operator?

Answer

Here's my example of using a functor:

#include <iostream>
#include <string>
struct Functor
{
    void operator()(const std::string text)
    { std::cout << text << "\n";}  
};  

// Usage:  
int main()
{
    Functor f;
    f("Hello World!");
    return EXIT_SUCCESS;
}

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles