我可以肯定这是一个编译器错误或诸如此类的问题:如果不同翻译单元中的两种类型具有相同的名称,并且是从模板类的嵌套类派生的,则dynamic_cast将在其中一个翻译单元中失败。
就我而言,我使用以A
两个翻译单元命名的两种不同类型(它们是测试用例)。在每个对象obj
中,我都有一个类型的对象A
。A
源自抽象基础root_type
。obj_ref
具有类型root_type&
,并绑定到obj
。试图投obj_ref
来A&
投std::bad_cast
。
#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 {};
因此,您的程序具有未定义的行为,并且不需要编译器来诊断问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句