c++ - 这个模板类型推导和重载解析是如何工作的?

标签 c++ templates language-lawyer c++17 argument-dependent-lookup

代码#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 .

导致不明确的重载错误。所以我有两个问题:

问题

  1. 如何 container是在代码 #1 中推导出来的吗?

    据我所知,模板实例化期间的类型推导无法通过成员类型回溯以找到封闭的类型(在本例中为 std::vector<int>)。

  2. 即使可以回溯,为什么能编译成功而没有引起模棱两可的重载错误?

最佳答案

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 没有这样的问题,您的 sortstd::sort 都是有效的候选者,然后会导致模棱两可的重载错误。

关于c++ - 这个模板类型推导和重载解析是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49748423/

相关文章:

c++ - 什么时候应该使用模板,什么时候重载函数?

c++ - 下面的代码是否应该按照 C++ 标准编译?

c++ - 当显式模板实例化定义先于显式声明时,GCC 和 clang 不同意

c++ - 通过指针比较

c++ - 如何使用 C++ 中的模板从 json 中填充尽可能通用的 std::vector (11)?

c++ - 检查类是否继承自模板的任何模板实例化

python - python 中的自引用列表?

c++ - Visual C++ express 2010 程序入口点 ??1task_group_context@tbb@@QAE@XZ 无法位于动态链接库 tbb.dll 中

c++ - 使用 std::async 比非异步方法慢来填充 vector

c++ - 使用 CMake 构建 project.sln 时发布构建事件错误