简体   繁体   English

C ++全局外部“ C”朋友无法到达命名空间类上的私有成员

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

Please consider the code: 请考虑以下代码:

#include    <iostream>

using namespace std;

extern  "C"
void    foo( void );

namespace   A
{
    template< int No >
    class   Bar
    {
    private:
        friend  void    ::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;
    }
}

extern  "C"
void    foo( void )
{
    A::Bar< 0 >::private_func( 1 );
}

int main( )
{
    cout << " ---- " << endl;
    foo( );
}

G++ gives: G ++提供:

> g++ -Wall -o extern_c extern_c.cpp
extern_c.cpp: In function ‘void foo()’:
extern_c.cpp:20:7: error: ‘static void A::Bar<No>::private_func(int) [with int No = 0]’ is private
extern_c.cpp:29:31: error: within this context

If I comment the namspace A , it will compile and run correctly. 如果我评论namspace A ,它将编译并正确运行。

What am I missing? 我想念什么?

I looked related topics, but could not find any that fits in my problem. 我查看了相关主题,但找不到适合我的问题的任何主题。

Thanks people. 谢谢大家


EDIT: 编辑:

I am now convinced that extern "C" has nothing to do with the problem. 我现在确信, extern "C"与问题无关。 Please ignore it. 请忽略它。

It's a g++ bug. 这是一个g ++错误。 Exists in 4.4, fixed in 4.6. 存在于4.4中,已在4.6中修复。

UPD: It seems that it's triggered by a combination of template and namespace . UPD:它似乎是由templatenamespace的组合触发的。 extern "C" is not relevant, as it may be commented out and the error remains. extern "C" ,因为它可能已被注释掉并且错误仍然存​​在。

I don't know the explanation, but if you put foo( ) into a namespace, it works. 我不知道其解释,但是如果将foo()放入命名空间中,它将起作用。

#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 )

You need to declare the friend as extern "C". 您需要将朋友声明为extern“ C”。 Your current friend declaration finds a friend foo in the global namespace that has C++ name mangling. 您当前的好友声明在全局名称空间中找到具有C ++名称修饰的好友foo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM