繁体   English   中英

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

[英]c++: Calling a template method of a base class from a template child class though multilevel inheritance

我想从子类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,但无法解决这个问题。

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

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

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

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

所以像这样:

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

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

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

由完全实例化的template类型B<int> ,因此A的类别不再依赖于(本地未确定的) template参数。 类似地, ->A<int>是完全实例化的template类型,因此::Func不再依赖于(本地未确定的) template参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM