[英]bad_cast exception thrown when doing downcasting from Base class object by reference to derived class object
[英]C++ bad_cast exception casting *this to derived template class
我正在尝试虚拟模板功能的实现。 当this
指针转换为指向子类模板的指针时,它可以工作,但是当我将*this
转换为对子类的引用时,我无法使其正常工作。
template <typename T> struct BB; // forward reference (not bound until instantiation in main)
struct AA
{
virtual ~AA(){}
template <typename T>
void operator()(T && t)
{
dynamic_cast<BB<T>*>(this)->operator()(std::forward<T>(t)); // works!
dynamic_cast<BB<T>&>(*this)(std::forward<T>(t)); // compiles but throws bad_cast
}
};
template <typename T>
struct BB : AA
{
void operator()(T t) { std::cout << "BB::operator()" << std::endl; }
};
int main()
{
BB<int> bb;
int k = 5;
static_cast<AA&>(bb)(k);
}
在您的通话中static_cast<AA&>(bb)(k);
, T
推导为int &
,并且包含*this
的最派生对象不是BB<int &>
类型。 因此,这两个强制转换都将失败,并且指针间接产生未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.