c++的bad_cast异常将*this强制转换为派生模板类
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 &>
类型。所以这两个类型转换都失败了,指针间接地产生了未定义的行为。
相关文章:
- 存储模板类型以强制转换回派生<T>
- 在 C++ 中将对象转换为派生类型
- 从基类实例调用派生类方法而不进行强制转换
- 从基指针到派生的强制转换问题
- C++将派生类转换为基类时'object slicing'期间发生的情况
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- C ++基础私有方法在将自身转换为派生类后可以访问吗?
- 调用不在基类中的派生类函数而不进行动态强制转换,以最大程度地提高性能
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 我们可以在不知道其真实类型的情况下将基类指针转换为派生类指针吗?
- 为什么从基转换为派生提供此功能?
- 将基本实例指针强制转换为派生实例指针是否合法?(实例不是派生实例)
- 从从该抽象类派生的 Python 对象强制转换C++抽象类C++
- 基类到派生类的强制转换向量
- 有没有办法复制派生类指针的向量而不将其强制转换为基类?
- 为什么此代码不将基类强制转换为 c++ 中的派生类?
- 如何在运行时将指向派生类的 void* 正确转换为指向基类的 void*
- C++转换派生类
- CRTP / 宏 / 避免强制转换派生类的指针
- 如何正确转换派生类