C++模板:派生类无法巩固基类功能,除非使用“ this->”

发布于 2025-02-11 01:11:50 字数 735 浏览 0 评论 0原文

此代码没有编译:

#include<iostream>
using namespace std;
template<class T>struct Base {
    void f(int) { cout << "Base::f() int\n"; }
};
template<class T>struct Derived:Base<T> {
    void g(int i) { f(i); } // should be this->f(i) to pass compile
};
int main(){
    Derived<char> obj;
    obj.g(1); // cfunction short
    return 0;
}

我在stackoverflow上搜索并搜索了搜索,它说在错误线中,我应该使用写作

void g(int i) { this->f(i); }

或是

void g(int i) { Base<T>::f(i); }

,它们可以使用。我尝试了无模板版本,不需要这个复杂的预选赛。只要f()g()不使用任何模板类型参数,我就不会考虑这两个函数对模板扣除的规则。

这是我应该添加额外资格的模板分辨率背后的一些隐藏规则,以及为什么我的原始代码无法编译?

This code doesn't compile:

#include<iostream>
using namespace std;
template<class T>struct Base {
    void f(int) { cout << "Base::f() int\n"; }
};
template<class T>struct Derived:Base<T> {
    void g(int i) { f(i); } // should be this->f(i) to pass compile
};
int main(){
    Derived<char> obj;
    obj.g(1); // cfunction short
    return 0;
}

I googled and search on stackoverflow, it says that in the error-line, I should use write either

void g(int i) { this->f(i); }

or

void g(int i) { Base<T>::f(i); }

Yes, they work. I tried none-template version, doesn't need this complex qualifier. As long as both f() and g() doesn't use any template type parameter, I didn't think of a rule on template deduction upon these 2 functions.

Is this some hidden rule behind template resolution that I should add extra qualifier, and why my original code fail to compile?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文