c++20linker-errorsldsuppress-warnings

Why am I getting "no matching literal operator" when trying to use sv literals?


I want to use the literal operators introduced in C++17 to create string views. But if I write:

#include <string_view>

// ...

auto name = "John Smith"sv;

in my code, compilation fails; clang++ says:

error: no matching literal operator for call to 'operator""sv' with arguments of types
'const char *' and 'unsigned long', and no matching literal operator template

and g++ says:

error: unable to find string literal operator 'operator""sv' with 'const char [4]', 'long
unsigned int' arguments

why are they not accepting the sv literal?


Solution

  • The sv literal is not in the global namespace by default; you have to first write:

    using namespace std::literals::string_view_literals;
    

    (or std::literals, or std::string_view_literals), and then your code will work (GodBolt).