模板多态性不工作? [英] Template Polymorphism not Working?

查看:92
本文介绍了模板多态性不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个小模板层次结构,并尝试使用类多态性。这里有一些示例代码(不编译)来演示它:

  template< typename T& 
struct A
{};

template< typename T>
struct B
{
B(A< B> *){}
};

struct C:public B< int>
{
C(A< C> * p):B< int>(p){} // error
}


int main(){
A< C> ac;
C c(& ac);
}



我的编译器(OS X上的gcc 4.01)会在指定的line:

 错误:没有匹配的函数调用'B< int> :: B(A& )'

但是根据我的逻辑假设,代码应该工作,因为

  C == B< int> 
B< int> == B< T>

=> A< C> == A< B< T> >

有人可以指出我的错误以及如何解决它吗?






EDIT



我的问题不能通过常规继承树解决,因为模板是静态的,以识别多态性。这将是合法的然后投入 C> B < int>>>< / em>以强制多态性,尽管从设计的角度来说是可怕的。

  struct C:public B< int& 
{
C(A< C> * p):B< int>((A< B int> *)p){}
}

这个问题有没有好的解决方案?

解决方案

A< B < int>>与A< C,即使C来自B < int>。



因此,构造函数C的参数,类型A< C> *与构造函数B < int>,其为A < B <
使用模板化构造函数:



pre> template< typename T>
struct B
{
template<类型名E>
B(E *){}
};

struct C:public B< int>
{
template<类型名E>
C(E * p):B< int>(p){}
}

但是,问题太抽象,不能给出解决方案...


I'm building a small template hierarchy and try to make use of class polymorphism. Here's some example code (which does not compile) to demonstrate it:

template<typename T>
struct A
{};

template<typename T>
struct B
{
    B (A<B> *) {}
};

struct C : public B<int>
{
    C(A<C> *p) : B<int>(p) {} // error
};


int main() {
    A<C> ac;
    C c(&ac);
}

My compiler (gcc 4.01 on OS X) throws the following error on the specified line:

error: no matching function for call to ‘B<int>::B(A<C>*&)’

But from my logical assumptions the code should work because

C       == B<int>
B<int>  == B<T>

=> A<C> == A<B<T> >

Can someone point out where my mistake lies and how to fix it, please?


EDIT

The answer seems to be that my problem can not be solved by regular inheritance trees because templates are to static to recognize polymorphism. Would it be legal then to cast A< C > to A< B < int > > to force polymorphism although it's horrible from a design standpoint?

struct C : public B<int>
{
    C(A<C> *p) : B<int>((A<B<int> > *)p) {}
};

Is there any "good" solution for this problem?

解决方案

A < B < int > > is not the same type as A < C >, even if C is derived from B < int >.

So the parameter of constructor C, of type A < C >* is not compatible with the parameter requested of constructor B< int>, which is A < B < int> >.

Later edit: Use templated constructors:

template<typename T>
struct B
{
    template< typename E>
    B (E *) {}
};

struct C : public B<int>
{
    template< typename E>
    C(E *p) : B<int>(p) {}
};

However, the problem is too abstract to give a solution...

这篇关于模板多态性不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆