C++11: Why is private member template accessible outside class?

后端 未结 2 466
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 02:49

I just happened to find that a nested private template class can be accessed directly outside the enclosing class using a using directive:

class         


        
2条回答
  •  心在旅途
    2020-12-29 03:21

    This is definitely a compiler bug, and actually one that has been known for quite some time: GCC #47346 (first reported in Jan 2011) and Clang #15914 (first reported May 2013). Your __tklass is clearly private, and the template alias is not marked friend, so this should be a simple access error.

    The simplest reproduction is from the Clang example attachment, this version compiles on both gcc 4.9.2 and clang 3.5.0, though should definitely compile on neither:

    class A
    {
      class B {};
    };
    
    template
    using T = A::B;
    
    T t;
    

    Clang is strictly better than GCC on this front however, as this particular bug seems to occur only with template aliases. A "workaround" (if you need such a thing for cases that the compiler allows incorrectly...) would be to revert back to pre-C++11 template aliasing:

    template 
    struct T {
        using type = A::B;
    };
    
    T::type t;
    

    That code correctly fails to compile with clang (error: 'B' is a private member of 'A'), but still compiles fine with gcc.

提交回复
热议问题