加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c:通过多级继承从模板子类调用基类的模板方法

发布时间:2020-12-16 07:08:44 所属栏目:百科 来源:网络整理
导读:我想从子类D调用基类A的方法,通过C :: A和B :: A继承它. template class PTypeclass A{public: template class ChildClass void Func( void ) { std::cout "Called APType::FuncChildClass" std::endl; }};template class PTypeclass B : public APType{};te
我想从子类D调用基类A的方法,通过C :: A和B :: A继承它.

template <class PType>
class A
{
public:
    template <class ChildClass>
    void Func( void )
    {
        std::cout << "Called A<PType>::Func<ChildClass>" << std::endl;
    }
};

template <class PType>
class B : public A<PType>
{
};

template <class PType>
class C : public A<PType>
{
};

class D : public B<int>,public C<int>
{
public:
    D()
    {
        static_cast<B<int>*>( this )->A<int>::Func<D>();
        static_cast<C<int>*>( this )->A<int>::Func<D>();
    }
};

这按预期工作,D在初始化时使用子类的模板参数调用B :: A :: Func和C :: A :: Func.但是,当D是模板类时,这似乎不起作用.

template <class PType>
class D2 : public B<PType>,public C<PType>
{
public:
    D2()
    {
        //expected primary-expression before ‘>’ token
        //expected primary-expression before ‘)’ token
        static_cast<B<PType>*>( this )->A<PType>::Func< D2<PType> >();
        static_cast<C<PType>*>( this )->A<PType>::Func< D2<PType> >();
    }
};

问题似乎是模板参数D2到Func,但无法解决这个问题.

解决方法

当您使用其值/类型/模板状态取决于模板类型参数的名称时,必须手动消除编译器的名称.

这是为了使解析更容易,并且可以在将类型传递到模板之前很久就完成.

您可能认为这显然是模板函数调用,但<和>可以进行比较,模板函数可以是值或类型或其他.

默认情况下,假定此类从属名称为值.如果您希望将它们视为一种类型,请使用typename.如果要将其中一个视为模板,请使用模板作为关键字.

所以像这样:

static_cast<B<PType>*>( this )->template A<PType>::template Func< D2<PType> >();

现在,当您与完全实例化的模板交互时,这不是必需的.所以:

static_cast<B<int>*>( this )->A<int>::Func< D2<PType> >();

由完全实例化的模板类型B< int>组成,因此A的类别不再依赖于(本地未确定的)模板参数.类似地,– > A< int>是一个完全实例化的模板类型,因此:: Func不再依赖于(本地未确定的)模板参数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读