代码#1
#include <iterator>
#include <algorithm>
#include <iostream>
#include <vector>
template <typename container>
void sort(typename container::iterator beginning,
typename container::iterator end)
{
std::cout << "calling custom sorting function\n";
}
int main()
{
std::vector<int> v{1, 2, 3};
sort(v.begin(), v.end());
}
Wandbox .
代码说明
它将调用 std::sort
函数,由 ADL 找到。通过下面的代码:
代码#2
#include <iterator>
#include <algorithm>
#include <iostream>
#include <vector>
template <typename Iterator>
void sort(Iterator beginning,
Iterator end)
{
std::cout << "calling custom sorting function\n";
}
int main()
{
std::vector<int> v{1, 2, 3};
sort(v.begin(), v.end());
}
Wandbox .
导致不明确的重载错误。所以我有两个问题:
问题
如何
container
是在代码 #1 中推导出来的吗?据我所知,模板实例化期间的类型推导无法通过成员类型回溯以找到封闭的类型(在本例中为
std::vector<int>
)。即使可以回溯,为什么能编译成功而没有引起模棱两可的重载错误?
最佳答案
How
container
was deduced in code #1?
由于non-deduced context,在模板参数推导时无法推导,
1) The nested-name-specifier (everything to the left of the scope resolution operator
::
) of a type that was specified using a qualified-id:
这意味着您的 sort
根本不会被考虑用于重载决议,然后 std::sort
被毫无歧义地调用。
代码 #2 没有这样的问题,您的 sort
和 std::sort
都是有效的候选者,然后会导致模棱两可的重载错误。
关于c++ - 这个模板类型推导和重载解析是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49748423/