如何从模板化基类调用模板化派生类上的成员

How can I call a member from a templated base class on a templated derived class?

本文关键字:成员 派生 基类 调用      更新时间:2023-10-16

这样设置:

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

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

前提是你的代码在Clang 3.2(见这里)和GCC 4.7.2(见这里)上可以很好地编译,我不认为有理由使用Base<E>:::只使用d->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();