dynamic_cast 动态类型为转换类型的对象失败

dynamic_cast fails for an object whose dynamic type is the casted type

我很确定这是一个编译器错误或其他问题:如果不同翻译单元中的两种类型具有相同的名称并且派生自模板 class 的嵌套 classes,dynamic_cast 将在其中一个翻译单元中失败。

在我的例子中,我在两个翻译单元(它们是测试用例)中使用了两种名为 A 的不同类型。在每个中,我都有一个 A 类型的对象 objA 派生自抽象基础 root_typeobj_ref 的类型为 root_type& 并绑定到 obj。尝试将 obj_ref 转换为 A& 会抛出 std::bad_cast.

mixin.hpp
#pragma once
template <typename... Types>
struct mixin
{
    struct root_type
    {
        virtual ~root_type() = default;
    };
};
use_AB.cpp
#include "mixin.hpp"
struct A;
struct B;
struct A : mixin<A, B>::root_type{};

void use_AB()
{
    using root_type = mixin<A, B>::root_type;
    A a;
    root_type &a_ref = a;
    dynamic_cast<A&>(a_ref);
}
use_A.cpp
#include "mixin.hpp"
struct A;
struct A : mixin<A>::root_type {};

void use_A()
{
    using root_type = mixin<A>::root_type;
    A a;
    root_type &a_ref = a;
    //////////////////////////////////////////
    dynamic_cast<A&>(a_ref); // throws - dynamic_cast failure
    //////////////////////////////////////////
}
main.cpp
void use_A();
void use_AB();

int main()
{
    use_A();
    use_AB();
    return 0;
}

怎么回事?

编译器是 VisualStudio 2015 (v140)。

您给出 struct A 两个不同的定义,违反了单一定义规则:

struct A : mixin<A, B>::root_type{};
struct A : mixin<A>::root_type {};

因此你的程序有未定义的行为,编译器不需要诊断问题。