调用基的模板函数成员,当它被调用相同的名称时

Calling template function member of the base when it's called the same name

本文关键字:调用 函数 成员      更新时间:2023-10-16

我试图理解为什么以下代码无法编译(使用 gcc 4.8.2):

struct A {
    template <typename T>
    T f() {return T(0);}
};
struct B : A {
    using MyT = int;
    MyT f() {return (A *)this->template f<MyT>();}
};
int main()
{
    B b;
    std::cout << b.f() << std::endl;
    return 0;
}

如果我在 base 中将名称从 f 更改为 f1,那么下面的编译就可以了:

struct A {
    template <typename T>
    T f1() {return T(0);}
};
struct B : A {
    using MyT = int;
    MyT f() {return this->template f1<MyT>();}
};

仅仅因为运算符优先级,您将f函数的结果强制转换为A*,而不是将this转换为A*,实际上最好使用 static_cast

MyT f() {return static_cast<A*>(this)->f<MyT>();}

这将起作用。而且你还有名字隐藏,你只是这样做:

struct B : A {
    using MyT = int;
    using A::f;
    MyT f() {return this->f<MyT>();}
};