c++ - 候选函数集

标签 c++ overloading language-lawyer

假设我有以下功能:

#include <iostream>
class A{ };
class B{ };

void foo(A&& a){ std::cout << "A&&" << std::endl; };
void foo(A& a){ std::cout << "A&" << std::endl; };
void foo(B& b, B& bb){ std::cout << "B&, B&" << std::endl; };
void foo(B& b){ std::cout << "B&" << std::endl; };
void foo(const A& a){ std::cout << "const A&" << std::endl; };

A a;

int main()
{
    foo(a);
}

当我们调用函数 foo(a) 时,候选函数集是什么?标准是这样说的:

13.3.1.1.1 调用命名函数[over.call.func]

In unqualified function calls, the name is not qualified by an -> or . operator and has the more general form of a primary-expression. The name is looked up in the context of the function call following the normal rules for name lookup in function calls (3.4).

[...]

the argument list is the same as the expression-list in the call

因此,候选函数将是除foo(B&, B&) 之外的所有foo(参数个数不同)。是吗?

最佳答案

来自 [over.call.func]:

The name is looked up in the context of the function call following the normal rules for name lookup in function calls (3.4). The function declarations found by that lookup constitute the set of candidate functions.

这只是不合格的查找。所以候选函数是任何名为 foo 的函数。也就是说,所有这些:

void foo(A&& );
void foo(A& );
void foo(B& , B& );
void foo(B& );
void foo(const A& );

参数数量是否匹配或任何转换是否可能都无关紧要 - 第一步只是名称查找。这就是为什么该术语是候选函数。这些都是候选人,我们还没有排除任何东西。

与此分开,我们确定参数列表。这是您引用的第二个片段,完整内容如下:

Because of the rules for name lookup, the set of candidate functions consists (1) entirely of non-member functions or (2) entirely of member functions of some class T. In case (1), the argument list is the same as the expression-list in the call.

我们这里是案例 1。所以在这种情况下,我们有 5 个候选函数和一个 a 的参数列表。

关于c++ - 候选函数集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31186912/

相关文章:

java - 使用 .equals() 比较两个不同初始化的对象似乎不起作用

c++ - 在具有一个元素的列表上强制 std::vector 重载而不是 int 重载

c++ - 使用 `&&` 和 `const` 限定符重载 operator== 会导致 C++20 中的歧义

c++ - Travis CI 似乎从错误的 stdlib 中读取

c++ - Reinterpret_cast 在 C++ 中的使用

c++ - 为什么结构的 sizeof 不等于每个成员的 sizeof 之和?

c++ - 你如何着手制作基于 tcp 的可靠 udp 协议(protocol)?

c++ - QtCreator如何识别正在使用的是哪个override?

c - 是否要求指向两个不同本地空对象的指针比较不相等?

c++ - `std::basic_string::operator[]` 能否返回一个 "distant"保护页 nul 终止符?