我有以下代码:
struct Base
{
virtual ~Base(){};
};
template<class T>
struct Derived : public Base
{};
int main()
{
Derived<int> d;
Base *pD = &d;
if(dynamic_cast<Derived<const int>*>(pD))
{
std::cout << "const" << std::endl;
}
if(dynamic_cast<Derived<int>*>(pD))
{
std::cout << "non-const" << std::endl;
}
}
我希望两个 dynamic_casts 都返回一个有效的指针,因为新类型的 cv 限定较少。谁能向我解释我错过了什么?有什么方法可以识别 Derived<XYZ>
忽略给定 Base
的 cv 限定符指针?
最佳答案
从编译器的角度来看,Derived<int>
和 Derived<const int>
相距const char*
和 struct MyBox
.换句话说,他们之间没有任何关系。
关于c++ - dynamic_cast 派生模板到较少的 cv 限定指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36849950/