依赖于参数的查找和函数模板

chi*_*ang 6 c++ templates function-templates argument-dependent-lookup

这是一个例子:

#include <string>
#include <algorithm>
#include <memory>

using std::string;

int main()
{
    string str = "This is a string";

    // ok: needn't using declaration, ADL works
    auto it = find(str.begin(), str.end(), 'i');

    // error: why ADL doesn't work?
    std::shared_ptr<string> sp = make_shared<string>(str);
}
Run Code Online (Sandbox Code Playgroud)

当我试图编译这个程序时,编译器抱怨:

error: no template named 'make_shared'; did you mean 'std::make_shared'?
        std::shared_ptr<string> sp = make_shared<string>(str); // error...
                                     ^~~~~~~~~~~
                                     std::make_shared
Run Code Online (Sandbox Code Playgroud)

我猜第一个函数find不需要using声明,因为依赖于参数的lookup(ADL):编译器会搜索名称空间string(即std)的定义find.但对于第二个函数make_shared,它似乎ADL不起作用:我必须使用std::make_sharedusing声明.我知道两个函数模板的定义是不同的:前者将其模板参数之一(typename T或类似的东西)作为函数参数类型并返回相同的类型.后者将函数参数包作为函数参数,其返回类型是另一个模板参数.禁用这个区别ADL吗?或者你能帮助回答这个问题并提供一些参考资料吗?

Ker*_* SB 1

参数相关查找适用于非限定函数调用表达式。对于“普通”函数以及函数模板特化来说都是如此。

但是,当您为模板函数提供显式模板参数时,表达式在语法上看起来不像函数调用:

foo<3>(x)  //   "foo less than three?"
Run Code Online (Sandbox Code Playgroud)

这就是为什么这些情况不会触发 ADL。然而,一旦知道某个名称是模板,ADL 就适用!

template <int> void foo();

foo<double, 5, T>(x);   // uses ADL
Run Code Online (Sandbox Code Playgroud)