![](/img/trans.png)
[英]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.