请考虑代码:
#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给出:
> 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
如果我评论namspace A,它将编译并正确运行.
我失踪了什么
我看了相关的话题,但找不到符合我问题的东西.
> C++: namespace conflict between extern “C” and class member
> Why this friend function can’t access a private member of the class?
感谢人.
编辑:
我现在相信外部的“C”与这个问题无关.
请忽略它.
解决方法
我不知道这个解释,但是如果你把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( ); }
结果:
bbcaponi@bbcaponi friends]$g++ -Wall namespace_friend.cpp -o namespace_friend [bbcaponi@bbcaponi friends]$./namespace_friend ---- A::Bar< 0>::private_func( 1 )