当编译器尝试解析时,它会在全局命名空间中i.template hi<T>();
找到,而不是在( ideone ) 上的方法。为什么?hi
hi
i
#include <cstdio>
// Define 'hi' and 'bye' in the global namespace; these should *not* be used
template<typename T> struct hi { };
template<typename T> struct bye { };
// Foo needs to be templated for Foo::Inner to be a dependent type (I think)
template<typename T>
struct Foo
{
struct Inner {
// This is a plain-old templated member function of Inner, yes?
template<typename U>
void hi() { std::printf("hi!\n"); }
// This is a plain-old member function of Inner
void bye() { std::printf("bye!\n"); }
};
void sayStuff()
{
Inner i;
i.template hi<T>(); // Fails to compile -- finds global hi instead of member
i.bye(); // Compiles fine, finds member
}
};
int main() {
Foo<int> f;
f.sayStuff();
return 0;
}
我正在使用 g++ 4.9.1/4.9.2 ( -std=c++11
)。确切的错误信息:
prog.cpp: In member function 'void Foo<T>::sayStuff()':
prog.cpp:19:5: error: invalid use of 'struct hi<T>'
i.template hi<T>();
^
此代码适用于 Clang 和 VS2013,但会在 g++ 和 EDG 中生成错误。但是哪些编译器是正确的?
除了更改会员姓名之外,还有什么办法可以解决这个问题吗?std
在我的真实代码中,当命名空间中的类型(例如,通过 导入using namespace std
)与我的成员函数之一具有相同的名称时,就会出现冲突。显然,我希望我的实现代码是健壮的,并且不会导致用户代码中的随机名称冲突。