基类中的私有静态成员

Private static member in base class

本文关键字:静态成员 基类      更新时间:2023-10-16
#include <iostream>
#include <string>
class Base
{
    static std::string s;
};
template<typename T>
class Derived
    : Base
{
public:
    Derived()
    {
        std::cout << s << std::endl;
    }
};
std::string Base::s = "some_text";    
int main()
{
    Derived<int> obj;
}

该程序编译并正常运行。静态变量s在私有继承的基类中是私有的。派生类如何访问它?

如果派生类不是模板,编译器会报错访问私有变量。

[aminasya@amy-aminasya-lnx c++]$ g++ --version
g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

这绝对是一个GCC bug,相当于GCC bug 58740:

class A {
    static int p;
};
int A::p = 0;
template<int=0>
struct B : A {
    B() {(void)p;}
};
int main() {
    B<>();
}

这个bug仍然是打开的,并且这个代码仍然可以在5.1上编译。GCC在模板成员访问方面有问题,这只是另一个这样的例子。

我认为这是一个编译器错误,因为它可以用gcc编译,而不是clang。

编辑:作为一个额外的数据点,这个错误似乎没有被修复,因为我可以在gcc 4.9.2和5.1中重现。

这是g++ 4.8.4中的一个bug。只有当Derived是模板且成员为静态时,代码才会编译。

测试:

    模板静态编译
  • 没有模板静态失败
  • 模板非静态失败
  • 模板非静态失败