https://gcc.gnu.org/bugzilla/show_bug.cgi?id=118302

            Bug ID: 118302
           Summary: Invalid 'static_cast' from derived type to private
                    based type is not rejected during in-class
                    initialization of static const member of template
                    class
           Product: gcc
           Version: 15.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: wangbopku15 at gmail dot com
  Target Milestone: ---

GCC generates no error for the invalid 'static_cast' statement in the following
test:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

struct Base {};

struct Derived : private Base {};

template <typename T> struct A {
      static const int N = sizeof(static_cast<Base>(Derived()));
};

int main(){
        A<int> aa;
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

As a comparison, clang rejects it with:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

<source>:6:53: error: cannot cast 'Derived' to its private base class 'Base'
    6 |       static const int N = sizeof(static_cast<Base>(Derived()));
      |                                                     ^
<source>:3:18: note: declared private here
    3 | struct Derived : private Base {};
      |                  ^~~~~~~~~~~~
<source>:6:53: error: cannot cast 'Derived' to its private base class 'Base'
    6 |       static const int N = sizeof(static_cast<Base>(Derived()));
      |                                                     ^
<source>:10:16: note: in instantiation of template class 'A<int>' requested
here
   10 |         A<int> aa;
      |                ^
<source>:3:18: note: declared private here
    3 | struct Derived : private Base {};
      |                  ^~~~~~~~~~~~
2 errors generated.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

MSVC with: 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

<source>(6): error C2243: 'type cast': conversion from 'Derived *' to 'Base &&'
exists, but is inaccessible
<source>(6): note: the template instantiation context (the oldest one first) is
<source>(10): note: see reference to class template instantiation 'A<int>'
being compiled
Compiler returned: 2

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Note that the code can be correctly rejected if 'A' is not a template class.

https://godbolt.org/z/6hdMsod6P

Reply via email to