g++ 中的模板函数匹配

发布于 2024-10-01 12:54:57 字数 414 浏览 0 评论 0原文

我遇到了一个奇怪的问题,并且想知道为什么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦醒时光 2024-10-08 12:54:57

编译器从当前范围开始检查候选范围的所有范围。它在直接作用域中找到名为 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.

旧城烟雨 2024-10-08 12:54:57

参考C++03部分

3.4.1 不合格名称查找

在 3.4.1 列出的所有情况下,都会按照每个相应类别中列出的顺序在范围中搜索声明; 一旦找到名称声明,名称查找就会结束。如果没有找到声明,则程序格式错误。

在您的代码示例中,编译器在当前作用域中找到名称 f ,从而结束非限定名称查找,但函数原型不匹配,因此您会收到错误。

使用 :: 对其进行限定使其可以工作,因为随后会在全局命名空间中搜索该名称,并调用具有正确原型的 f

Refer to C++03 section

3.4.1 Unqualified name lookup

In all the cases listed in 3.4.1, the scopes are searched for a declaration in the order listed in each of the respective categories; name lookup ends as soon as a declaration is found for the name. If no declaration is found, the program is ill-formed.

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 the f with the correct prototype is called.

萌化 2024-10-08 12:54:57

编译器似乎正在尝试调用 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 ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文