简体   繁体   English

此模板类型推导和重载解析如何工作?

[英]How does this template type deduction and overload resolution work?

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

Code description 代码说明

It is gonna call the std::sort function, which is found by ADL. 它将调用std::sort函数,该函数由ADL发现。 Though the code below: 虽然代码如下:

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

Causes ambiguous overload error. 导致模糊的过载错误。 So I have two questions: 所以我有两个问题:

Questions 问题

  1. How container was deduced in code #1? 如何在代码#1中推断出container

    From what I know, type deduction during template instantiation cannot backtrack through member types to find the enclosing one ( std::vector<int> in this case). 据我所知,模板实例化期间的类型推导不能回溯成员类型以找到封闭的(在这种情况下为std::vector<int> )。

  2. Even if it could backtrack, why did it compile without causing ambiguous overload error? 即使它可以回溯,为什么编译时不会导致模糊的过载错误?

How container was deduced in code #1? 如何在代码#1中推断出container

It can't be deduced during template argument deduction because of 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: 1)使用qualified-id指定的类型的嵌套名称说明符(作用域解析运算符::左侧的所有内容):

That means your sort won't be considered for overload resolution at all, then std::sort is called without ambiguity. 这意味着您的sort根本不会被考虑用于重载解析,然后调用std::sort而不会产生歧义。

Code #2 doesn't have such issue, both your sort and std::sort are valid candidates then leads to ambiguous overloading error. 代码#2没有这样的问题,你的sortstd::sort都是有效的候选者,然后导致模糊的重载错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM