简体   繁体   中英

How to eliminate RTTI in sample code

I'm writing a kd tree, which I think is good enough at this point. I've put the whole template at http://private.org.il/Code%20Projects/kd%20tree%20w%20bb%20cache.zipx

One thing I'd like to do is eliminate RTTI, and specifically calls to dynamic_pointer_cast.

_____________________ Edit with more info _____________________

The relevant part is that I use three classes: an abstract node class, that requires it's derived classes to implement the isInternal() function.

There are two classes that derive from it - an internal node class (function returns true), and a leaf node class (function returns false). Therefore, once isInternal is called, I know to which of the two derived classes the pointer can be casted to.


The one routine I'm having problem eliminating the call is ApproxNearestNeighborNode, which provides an initial guess for the nearest neighbor search. Currently it looks like this

shared_ptr<kd_leaf_node> ApproxNearestNeighborNode(const kd_point &srcPoint) const
{
    unsigned int Depth = 0;
    shared_ptr<kd_node> Node(m_Root);

    while (Node->isInternal())
    {
        shared_ptr<kd_internal_node> iNode = dynamic_pointer_cast<kd_internal_node>(Node);

        if (srcPoint[Depth++%K] <= iNode->splitVal() || iNode->Right() == nullptr)
            Node = iNode->Left();
        else
            Node = iNode->Right();
    }

    shared_ptr<kd_leaf_node> lNode = dynamic_pointer_cast<kd_leaf_node>(Node);

    return lNode;
}

The two issues that baffle me is keeping the routine iterative, rather than recursive, and returning a smart pointer to the leaf node.

[OK, I think there's a way to do it using shared_from_this, I just hope there's a way to do it rewriting as little code as possible.]

Any other feedback would be appreciated, but off topic, so please send it by email.

As noted by πάντα ῥεῖ, you can replace dynamic_pointer_cast by static_pointer_cast . It seems that your Node->isInternal() check is meant to ensure the dynamic case always succeeds, so a simple search-and-replace is enough.

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