g++ 中的模板函数匹配
我遇到了一个奇怪的问题,并且想知道为什么 g++ 4.1.2 的行为方式如此。
精简到本质:
#include <iostream>
template<typename T>
inline void f(T x) { std::cout << x*x; }
namespace foo {
class A {
public:
void f() const { f(2); }
};
}
对 f(2)
的调用失败,因为编译器无法匹配模板函数 f
。 我可以使它与 ::f(2)
一起使用,但我想知道为什么这是必要的,因为它完全明确,并且就我(诚然已经过时)的匹配知识而言规则是这样的,这应该可行。
I'm having an odd problem, and am wondering why g++ 4.1.2 is behaving the way it does.
Stripped to its essentials:
#include <iostream>
template<typename T>
inline void f(T x) { std::cout << x*x; }
namespace foo {
class A {
public:
void f() const { f(2); }
};
}
The call to f(2)
fails because the compiler fails to match the template function f
.
I can make it work with ::f(2)
but I would like to know WHY this is necessary, since it's completely unambiguous, and as far as my (admittedly out of date) knowledge of the matching rules goes, this should work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器从当前范围开始检查候选范围的所有范围。它在直接作用域中找到名为
f
的函数,并停止搜索。您的模板版本永远不会作为候选版本进行检查。有关完整说明,请参阅命名空间和接口原理。
The compiler examines all scopes for a candidate, starting with the current scope. It finds a function named
f
in the immediate scope, and there stops the search. Your template version is never examined as a candidate.See Namespaces and the Interface Principle for a complete explanation.
参考C++03部分
在您的代码示例中,编译器在当前作用域中找到名称
f
,从而结束非限定名称查找,但函数原型不匹配,因此您会收到错误。使用
::
对其进行限定使其可以工作,因为随后会在全局命名空间中搜索该名称,并调用具有正确原型的f
。Refer to C++03 section
In your code sample the compiler finds a name
f
in the current scope thus ending the unqualified name lookup but there is a mismatch in the prototypes of the functions and so you get an error.Qualifying it with
::
makes it work because the name is then searched in the global namespace and thef
with the correct prototype is called.编译器似乎正在尝试调用 A::f 并由于参数而失败,这在某种程度上似乎很正常。如果使用非模板函数,是否会出现同样的错误?
It seems that the compiler is trying to call A::f and fails because of the argument, which seems normal in a way. Do you have the same error if you use a non template function ?