我有一个涉及嵌套命名空间和模板类的问题。我还能够创建测试用例,它会产生与实际代码相同的错误,但更具可读性。
使用 VS2012 和 2010 平台工具集编译以下代码会导致错误:
namespace A
{
namespace B
{
namespace C1
{
struct SMeasResult{};
}
namespace C2
{
struct SMeasResult{};
}
}
}
namespace C1Test
{
using namespace A::B::C1;
template<typename T>
class Fook
{
public:
void Yu()
{
SMeasResult Field;
}
};
}
namespace C2Test
{
using namespace A::B::C2;
template<typename T>
class Fook
{
public:
void Yu()
{
SMeasResult Field;
}
};
}
void m(){
C1Test::Fook<int> yu;
C2Test::Fook<int> me;
yu.Yu();
me.Yu();
}
具体报错如下:
1>------ Build started: Project: MultiVicomTest (Visual Studio 2010), Configuration: Debug Win32 ------
1> test.cpp
1>c:\code\test.cpp(27): warning C4101: 'Field' : unreferenced local variable
1> c:\code\test.cpp(26) : while compiling class template member function 'void C1Test::Fook<T>::Yu(void)'
1> with
1> [
1> T=int
1> ]
1> c:\code\test.cpp(49) : see reference to class template instantiation 'C1Test::Fook<T>' being compiled
1> with
1> [
1> T=int
1> ]
1>c:\code\test.cpp(43): error C2872: 'SMeasResult' : ambiguous symbol
1> could be 'c:\code\test.cpp(11) : A::B::C2::SMeasResult'
1> or 'c:\code\test.cpp(7) : A::B::C1::SMeasResult'
1> c:\code\test.cpp(42) : while compiling class template member function 'void C2Test::Fook<T>::Yu(void)'
1> with
1> [
1> T=int
1> ]
1> c:\code\test.cpp(50) : see reference to class template instantiation 'C2Test::Fook<T>' being compiled
1> with
1> [
1> T=int
1> ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
我不明白为什么符号“SMeasResult”对于编译器来说是不明确的,因为它在单独的命名空间中使用。 到目前为止我能发现的是,只有当类是模板化类时才会出现这个问题。删除模板定义后不会出现同样的问题。
如果我做错了什么,有人能告诉我吗?
最佳答案
在我看来,这实际上像是一个编译器错误。当您认为函数的 C1Test
版本编译时没有歧义时,我怀疑 namespace C1Test
中的 using 命名空间以某种方式甚至在 C2Test中徘徊
命名空间。
g++ 4.4 和 4.5 都可以很好地编译这段代码这一事实进一步证实了这一点。
关于c++ - 嵌套的命名空间和不明确的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18128979/