You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

显式对象访问受保护成员:模板函数调用子类protected方法编译失败的原因咨询

显式对象访问受保护成员:模板函数调用子类protected方法编译失败的原因咨询

嘿,我最近写C++代码时碰到个编译卡壳的问题,琢磨半天没搞明白,来请教下大伙!

先贴出我的代码:

class A {
public:
    template <class Self>
    void invokeUser(this Self&& self) {
        self.invokeProtected();
    }
};

template <typename... Bases>
class B : public Bases... {
protected:
    void invokeProtected() {}
};

int main() {
    B<A>{}.invokeUser();
}

编译时直接报错,错误信息如下:

error: 'invokeProtected' is a protected member of 'B'
note: in instantiation of function template specialization 'A::invokeUser<B
>'

我有点搞不懂的是,这里的self明明就是B<A>的实例引用啊,从这个上下文来看,按理说应该能访问它的protected成员吧?毕竟A是B<A>的基类,而且调用还是在基类的成员函数里发起的。

现在我整不明白,这是C++标准明确禁止的行为,还是Clang编译器的bug呢?有没有大佬能给我捋捋?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 08:45:30