【问题标题】:c++: Calling a template method of a base class from a template child class though multilevel inheritancec ++:通过多级继承从模板子类调用基类的模板方法
【发布时间】:2014-06-19 18:43:15
【问题描述】:

我希望从通过 C::A 和 B::A 继承的子类 D 调用基类 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> >();
    }
};

问题似乎是 Func 的模板参数 D2,但除此之外无法解决。

【问题讨论】:

  • 试试static_cast&lt;B&lt;PType&gt;*&gt;(this)-&gt;template A&lt;PType&gt;::Func&lt; D2&lt;PType&gt; &gt;();

标签: c++ templates inheritance casting


【解决方案1】:

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

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

您可能认为这显然是一个template 函数调用,但&lt;&gt; 可以是比较,模板函数可以是值或类型或其他。

默认情况下,这些依赖名称被假定为值。如果您希望他们将其视为一种类型,请使用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&lt;int&gt; 组成,因此A 的类别不再依赖于(本地未确定的)template 参数。同样,-&gt;A&lt;int&gt; 是完全实例化的 template 类型,因此 ::Func 不再依赖于(本地未确定的)template 参数。

【讨论】:

    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2016-04-26
    相关资源
    最近更新 更多