2016-04-25 21 views
0

我有下面的代码:的dynamic_cast衍生模板较少CV-合格的指针

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-合格。任何人都可以向我解释我错过了什么吗?给定Base指针,有什么办法可以识别Derived<XYZ>忽略cv限定符吗?

回答

3

从编译器的角度来看,Derived<int>Derived<const int>const char*struct MyBox相差甚远。换句话说,他们之间没有任何关系。

3

您很困惑编译器正在查看哪种类型。正在减去const指的是不是模板参数的类型。如果你有

if(dynamic_cast<const Derived<int>*>(pD)) 
{ 
    std::cout << "const" << std::endl; 
} 

if(dynamic_cast<Derived<int>*>(pD)) 
{ 
    std::cout << "non-const" << std::endl; 
} 

然后这两个输出将打印。

一个something<sometype>是一个完全不同的类型,然后一个something<some_other_type>const something<sometype>只是const版本的something<sometype>

+0

我不太看怎么'东西'是'什么<常量some​​type。这时候>'如此不同?我的印象是,const在编译过程中被强制执行,并且基本上都是在执行之后。为什么动态转换的运行时检查仍然区分2? – Araex