【发布时间】:2017-11-28 12:22:21
【问题描述】:
我知道这个问题有点宽泛和不精确,但这就是我想要的:
struct DynTyped { /* HOW? */ };
class Animal : public DynTyped {};
class Dog : public Animal {};
class Cat : public Animal {};
// expect to work
Animal* a1 = new Dog;
Dog* d1 = DOWNCAST<Dog*>(a1);
d1->hello();
// expect to throw
Animal* a2 = new Cat;
Dog* d2 = DOWNCAST<Dog*>(a2);
d2->hello();
我可以做到的一种方法是在基类中设置一个字段。
class Animal {
enum AnimalType { Dog, Cat };
protected:
AnimalType type_;
}
但我想要一种在更高的基类中实现它的方法,因为我可能有一个形状基类,我不想再做那种类型字段的把戏了。
【问题讨论】:
-
使用 RTTI:
DOWNCAST只是dynamic_cast并在您的第二个示例中返回nullptr=> UB -
没有 RTTI:
DOWNCAST仍然是dynamic_cast但这次返回a2cast => UB -
我想在没有 RTTI 的情况下投掷。
-
Here's one way。但我确实警告你,它需要你的样板。很多样板。
-
@StoryTeller 太糟糕了!官方 LLVM 文档中的 that 怎么样?