【问题标题】:How can I call a member from a templated base class on a templated derived class? [closed]如何从模板派生类的模板基类调用成员? [关闭]
【发布时间】:2013-02-18 09:53:25
【问题描述】:

使用此设置:

template<int N>
struct Base {
    void foo();
};

class Derived : Base<1> {
    static void bar(Derived *d) {
        //No syntax errors here
        d->Base<1>::foo();
    }
};

一切正常。但是,在这个例子中:

template<class E>
struct Base {
    void foo();
};

template<class E>
class Derived : Base<E> {
    static void bar(Derived<E> *d) {
        //syntax errors here
        d->Base<E>::foo();
    }
};

我明白了:

error: expected primary-expression before '>' token
error: '::foo' has not been declared

有什么区别?为什么第二种会导致语法错误?

【问题讨论】:

  • 你用的是什么编译器?
  • 该死,错字。这个问题很垃圾。

标签: c++ templates token-name-resolution


【解决方案1】:

假设您的代码在 Clang 3.2(参见 here)和 GCC 4.7.2(参见 here)上编译良好,我看不出使用 Base&lt;E&gt;:: 的理由:只需使用 d-&gt;foo()

template<class E>
struct Base {
    void foo() { }
};

template<class E>
struct Derived : Base<E> {
    static void bar(Derived<E> *d) {
        //syntax errors here
        d->foo();
    }
};

int main()
{
    Derived<int> d;
    Derived<int>::bar(&d);
}

或者,您可以尝试使用template 消歧器:

d->template Base<E>::foo();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 2016-08-17
    • 2019-11-09
    • 2012-09-12
    • 1970-01-01
    • 2011-05-11
    • 2017-01-13
    • 1970-01-01
    相关资源
    最近更新 更多