为什么 `static_pointer_cast` 不适用于 ADL,而是需要显式的 `std::`?

Mar*_*utz 5 c++ shared-ptr argument-dependent-lookup unqualified-name static-pointer-cast

考虑

// https://godbolt.org/z/z5M9b9jzx
#include <memory>
#include <cassert>

struct B {};
struct D : B {};

int main() {
    std::shared_ptr<B> b = std::make_shared<D>();
    auto d = static_pointer_cast<D>(b);
    assert(d);
}
Run Code Online (Sandbox Code Playgroud)

我本来希望static_pointer_cast对解析为的不合格调用std::static_pointer_cast,因为b作为std::shared_ptr,应该引入namespace std使用 ADL。

为什么不呢?我需要std::shared_pointer_cast明确地编写以使其工作。

Fed*_*dor 3

https://en.cppreference.com/w/cpp/language/adl

尽管即使普通查找没有找到任何内容,也可以通过 ADL 解析函数调用,但对具有显式指定模板参数的函数模板的函数调用要求存在普通查找找到的模板的声明(否则,这是语法错误遇到未知名称后跟小于号字符)(C++20 之前)

在 C++20 模式下,您的代码可以正常编译,演示: https: //gcc.godbolt.org/z/b13q4hs68