Search code examples
c++stringstd

Why can I use std::stoul without std:: prefix?


I wonder why I can use std::stoul without std:: prefix. In other words, why does the code below compile and run (see for example on godbolt.org)

#include <string>
int main() { return stoul(std::string("123")); }

Solution

  • It works via Argument-dependent lookup (ADL):

    ... These function names are looked up in the namespaces of their arguments in addition to the scopes and namespaces considered by the usual unqualified name lookup.

    If the argument you pass to stoul is not from namespace std it will produce an error.

    For example:

    #include <string>
    
    int main() { return stoul("123"); }
    

    Produces (on MSVC):

    error C3861: 'stoul': identifier not found
    

    Live demo