簡體   English   中英

什么時候應用 ADL?

[英]When is ADL applied?

有3個例子:

一世。

typedef int foo;

namespace B
{
    struct S
    {
        operator int(){ return 24; }
    };
        int foo(B::S s){ return 0; }
}

int main()
{
    int t=foo(B::S()); //24, ADL does not apply
}

二、

namespace B
{
    struct S
    {
        operator int(){ return 24; }
    };
        int foo(B::S s){ return 0; }
}

int main()
{
    int t=foo(B::S()); //0, ADL applies
}

三、

namespace B
{
    struct S
    {
        operator int(){ return 24; }
    };
        int foo(B::S s){ return 0; }
}
int foo(B::S s){ return 12; }

int main()
{
    int t=foo(B::S()); //error: call of overloaded ‘foo(B::S)’ is ambiguous
                       //ADL applies
}

我不清楚 ADL 查找的實際條件是什么? 我需要參考標准來描述它。

這個標准段落澄清了,甚至有一個非常像你的第一個例子的例子。

3.4.1/3:

在 3.4.2 [basic.lookup.argdep] 中描述了對用作函數調用后綴表達式的非限定名稱的查找。 [注意:為了確定(在解析期間)表達式是否是函數調用的后綴表達式,通常的名稱查找規則適用。 3.4.2 中的規則對表達式的句法解釋沒有影響。 例如,

typedef int f;
namespace N {
  struct A {
    friend void f(A &);
    operator int();
    void g(A a) {
      int i = f(a);    // f is the typedef, not the friend
                       // function: equivalent to int(a)
    }
  };
}

由於該表達式不是函數調用,因此參數相關名稱查找 (3.4.2) 不適用並且未找到友元函數f -尾注]

你的第一個例子沒有說明 ADL。 在行中

int t=foo(B::S());

footypedef ed 到int

以下代碼對 ADL 有一些更好的說明。

#include <iostream>

namespace B
{
    struct S
    {
        operator int(){ return 24; }
    };

    int foo(S s){ return 100; }
    int bar(S s){ return 400; }
}

namespace C
{
    struct S
    {
        operator int(){ return 24; }
    };

    int foo(S s){ return 200; }
}

int bar(C::S s){ return 800; }

int main()
{
    // ADL makes it possible for foo to be resolved to B::foo
    std::cout << foo(B::S()) << std::endl;

    // ADL makes it possible for foo to be resolved to C::foo
    std::cout << foo(C::S()) << std::endl;

    // ADL makes it possible for bar to be resolved to B::bar
    std::cout << bar(B::S()) << std::endl;

    // ADL makes it possible for bar to be resolved to ::bar
    std::cout << bar(C::S()) << std::endl;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM