简体   繁体   中英

Why doesn't `static_pointer_cast` work with ADL, but requires explicit `std::`?

Consider

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

I'd've expected the unqualified call to static_pointer_cast to resolve to std::static_pointer_cast , because b , being a std::shared_ptr , should bring namespace std in using ADL.

Why doesn't it? I need to write std::shared_pointer_cast explicitly to make it work.

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)

In C++20 mode your code compiles fine, demo: https://gcc.godbolt.org/z/b13q4hs68

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM