【发布时间】:2020-10-04 18:22:52
【问题描述】:
我正在编写单元测试来练习涉及工厂类的各种代码路径。
工厂将std::unique_ptr 返回到基本类型:
class Base {};
class Derived1 : public class Base {};
class Derived2 : public class Base {};
std::unique_ptr<Base> Type::Factory(enum rtype) const {
switch(rtype) {
case d1: return std::make_unique<Derived1>();
case d2: return std::make_unique<Derived2>();
default: return std::make_unique<Derived1>();
}
}
所以在测试中我要确保返回正确的类型(工厂是剪切粘贴错误的温床)。
有没有办法检查返回的类型?
这:EXPECT_TRUE(typeid(Derived1), typeid(type.get()); 是错误的,因为 type.get() 是 Base 而不是传入的 rtype。
【问题讨论】:
-
我希望如果你这样做
typeid(*type.get())那么它会检查动态类型,不是吗? -
这能回答你的问题吗? Get object's type from pointer to base class at runtime 第二个答案说按照我的建议取消引用指针。
-
让
default返回Derived1看起来很可怕。 -
@underscore_d 这行得通。我正在搜索“比较底层类型”,但它没有五个链接。
标签: c++17 unique-ptr typeid dynamictype