在C++中,您可以通过将类和函数定义包装在匿名命名空间中来指定内部链接。您还可以显式实例化模板,但为了符合标准,模板的任何显式实例化都必须发生在相同的命名空间中。据我所知,这应该编译,但GCC无法执行:
namespace foo {
template<class T>
class bar {};
}
using namespace foo;
namespace {
template class bar<int>;
}
int main()
{
return 0;
}
出现以下错误:
namespace_test.cpp:11: error: explicit instantiation of 'class bar<int>' in namespace '<unnamed>' (which does not enclose namespace 'foo')
这很有趣,因为匿名命名空间应该只是指定链接,而不是真正作为命名空间,全局命名空间肯定包含foo,因为它包含每个命名空间。但即使这样也不行!
template<class T>
class bar {};
using namespace foo;
namespace {
template class bar<int>;
}
int main()
{
return 0;
}
同样出现错误,只是列出了全局命名空间:
namespace_test.cpp:11: error: explicit instantiation of 'class bar<int>' in namespace '<unnamed>' (which does not enclose namespace '::')
:/