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

坚强是说给别人听的谎言 提交于 2019-12-04 02:06:59

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 )

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!