c++ - 为什么 `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
明确地编写以使其工作。
解决方案
https://en.cppreference.com/w/cpp/language/adl
尽管即使普通查找什么也没找到,也可以通过 ADL 解析函数调用,但是对具有显式指定模板参数的函数模板的函数调用需要有普通查找找到的模板的声明(否则,它是语法错误遇到未知名称后跟小于字符)(C++20 前)
在 C++20 模式下,您的代码编译得很好,演示:https ://gcc.godbolt.org/z/b13q4hs68
推荐阅读
- java - 如何在客户端使用 jaxws 访问网络服务响应标头?
- microsoft-graph-api - Microsoft Graph - 订阅日历通知时出错
- html - Angular5/6 文本根据内容高度调整大小
- javascript - pushState 方法不起作用
- c# - 将文本从 C# 发送到 Xaml
- java - Java中的字符串到整数解决方案
- python - python:使用 np.vectorize 和 np.meshgrid 得到一个数组列表 - 误解
- ios - 如何根据背景图像的颜色更改 UILabel 文本颜色?(iOS)
- c# - ASP 网站只能通过删除命名空间来工作
- c# - 在c#中禁用果园菜单项