C++20 中模板的参数相关查找
Argument-dependent lookup for templates in C++20
以下程序在 C++20 中编译良好:
#include <memory>
struct A{ virtual ~A() = default; };
struct B: A {};
int main()
{
std::shared_ptr<A> p = std::make_shared<B>();
auto x = dynamic_pointer_cast<A>(p);
}
但在 C++17 中它会产生错误:
<source>: In function 'int main()':
<source>:9:14: error: 'dynamic_pointer_cast' was not declared in this scope; did you mean 'std::dynamic_pointer_cast'?
9 | auto x = dynamic_pointer_cast<A>(p);
| ^~~~~~~~~~~~~~~~~~~~
| std::dynamic_pointer_cast
In file included from /opt/compiler-explorer/gcc-11.1.0/include/c++/11.1.0/memory:77,
from <source>:1:
能否请您告诉我 C++20 中发生了什么变化以使其工作?
https://en.cppreference.com/w/cpp/language/adl
Although a function call can be resolved through ADL even if ordinary lookup finds nothing, a function call to a function template with explicitly-specified template arguments requires that there is a declaration of the template found by ordinary lookup (otherwise, it is a syntax error to encounter an unknown name followed by a less-than character)
(until C++20)
以下程序在 C++20 中编译良好:
#include <memory>
struct A{ virtual ~A() = default; };
struct B: A {};
int main()
{
std::shared_ptr<A> p = std::make_shared<B>();
auto x = dynamic_pointer_cast<A>(p);
}
但在 C++17 中它会产生错误:
<source>: In function 'int main()':
<source>:9:14: error: 'dynamic_pointer_cast' was not declared in this scope; did you mean 'std::dynamic_pointer_cast'?
9 | auto x = dynamic_pointer_cast<A>(p);
| ^~~~~~~~~~~~~~~~~~~~
| std::dynamic_pointer_cast
In file included from /opt/compiler-explorer/gcc-11.1.0/include/c++/11.1.0/memory:77,
from <source>:1:
能否请您告诉我 C++20 中发生了什么变化以使其工作?
https://en.cppreference.com/w/cpp/language/adl
Although a function call can be resolved through ADL even if ordinary lookup finds nothing, a function call to a function template with explicitly-specified template arguments requires that there is a declaration of the template found by ordinary lookup (otherwise, it is a syntax error to encounter an unknown name followed by a less-than character) (until C++20)