C++ global extern “C” friend can't reach private member on namespaced class

前端 未结 3 2423
轻奢々
轻奢々 2021-02-20 14:46

Please consider the code:

#include    

using namespace std;

extern  \"C\"
void    foo( void );

namespace   A
{
    template< int No >
           


        
3条回答
  •  生来不讨喜
    2021-02-20 14:52

    I don't know the explanation, but if you put foo( ) into a namespace, it works.

    #include    
    
    using namespace std;
    
    namespace C
    {
        extern  "C"
        void    foo( void );
    }
    
    namespace   A
    {
        template< int No >
        class   Bar
        {
        private:
            friend  void    C::foo( void );
    
            static void private_func( int n );
        };
    
        template< int No >
        void    Bar< No >::private_func( int n )
        {
            cout << "A::Bar< " << No << ">::private_func( " << n << " )" << endl;
        }
    }
    
    
    namespace C
    {
        extern  "C"
        void    foo( void )
        {
            A::Bar< 0 >::private_func( 1 );
        }
    }
    
    int main( )
    {
        cout << " ---- " << endl;
        C::foo( );
    }
    

    And the result:

    bbcaponi@bbcaponi friends]$ g++ -Wall namespace_friend.cpp -o namespace_friend
    [bbcaponi@bbcaponi friends]$ ./namespace_friend
     ----
    A::Bar< 0>::private_func( 1 )
    

提交回复
热议问题