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

前端 未结 3 2444
轻奢々
轻奢々 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:50

    It's a g++ bug. Exists in 4.4, fixed in 4.6.

    UPD: It seems that it's triggered by a combination of template and namespace. extern "C" is not relevant, as it may be commented out and the error remains.

    0 讨论(0)
  • 2021-02-20 14:52

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

    #include    <iostream>
    
    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 )
    
    0 讨论(0)
  • 2021-02-20 15:12

    You need to declare the friend as extern "C". Your current friend declaration finds a friend foo in the global namespace that has C++ name mangling.

    0 讨论(0)
提交回复
热议问题