首页 > 解决方案 > 为什么 `static_pointer_cast` 不能与 ADL 一起使用,但需要显式的 `std::`?

问题描述

考虑

// 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);
}

我希望无条件的调用来static_pointer_cast解决std::static_pointer_cast,因为b作为一个std::shared_ptr,应该namespace std使用 ADL。

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

标签: c++shared-ptrargument-dependent-lookupunqualified-name

解决方案


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

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

在 C++20 模式下,您的代码编译得很好,演示:https ://gcc.godbolt.org/z/b13q4hs68


推荐阅读