我将如何重新实施 dynamic_cast?

How would I re-implement dynamic_cast?

Stroustrup 书中的一个练习如下:

Write a template ptr_cast that works like dynamic_cast, except that it throws bad_cast rather than returning 0.

我设法想出的唯一解决方案是通过包装 dynamic_cast 适当的方式作弊:

template<typename Dst, typename Src>
Dst ptr_cast(Src* p) {
    Dst pt = dynamic_cast<Dst>(p);
    if (!pt)
        throw std::bad_cast();
    return pt;
}

class B {
public:
    virtual ~B();
};

B::~B() {}

class D : public B {};
class C {};

int main() {
    B* pb = new D;
    D* pd = ptr_cast<D*>(pb);  // passes
    C* pc = ptr_cast<C*>(pb);  // throws as planned

    return 0;
}

不过,我一直怀疑这不是作者的意思。有人有更好的主意吗?该项目标有一颗星,这意味着它一定是非常明显的东西。

您的解决方案与 boost 中 polymorphic_cast 中的解决方案几乎完全匹配:

//  Runtime checked polymorphic downcasts and crosscasts.
//  Suggested in The C++ Programming Language, 3rd Ed, Bjarne Stroustrup,
//  section 15.8 exercise 1, page 425.

template <class Target, class Source>
inline Target polymorphic_cast(Source* x)
{
    Target tmp = dynamic_cast<Target>(x);
    if ( tmp == 0 ) boost::throw_exception( std::bad_cast() );
    return tmp;
}

所以它可能是个好东西。