j4x*_*j4x 10 c++ templates namespaces extern
请考虑以下代码:
#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( );
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
如果我发表评论namspace A,它将编译并正确运行.
我错过了什么?
我看了相关的主题,但找不到任何适合我的问题.
谢谢大家.
编辑:
我现在确信这extern "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( );
}
Run Code Online (Sandbox Code Playgroud)
结果:
bbcaponi@bbcaponi friends]$ g++ -Wall namespace_friend.cpp -o namespace_friend
[bbcaponi@bbcaponi friends]$ ./namespace_friend
----
A::Bar< 0>::private_func( 1 )
Run Code Online (Sandbox Code Playgroud)