I am pretty sure this is a compiler bug or something: if two types in different translation units have the same name and derive from nested classes of a template class, dynamic_cast will fail in one of those translation units.
In my case, I use two different types named A
in two translation units (they were test cases). In each, I have an object obj
of type A
. A
is derived from an abstract base root_type
. obj_ref
has type root_type&
and is bound to obj
. Attempting to cast obj_ref
to A&
throws 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;
}
What’s going on?
Compiler is VisualStudio 2015 (v140).