Search code examples
c++c++17string-view

Creating an array of string_view elements throws error: unable to find string literal operator ‘operator""sv’ with


I have the following (modified) code where I want to create an array of std::string_view objects.

I see this error when compiling corresponding to each line

unable to find string literal operator ‘operator""sv’ with ‘const char [8]’, ‘long unsigned int’ arguments
         "Sensor2"sv,

The code:

#include <iostream>
#include <array>
#include <string_view>

struct Abc
{
    static constexpr std::array<std::string_view, 6> SomeValues = {
        "Sensor1"sv,
        "Sensor2"sv,
        "Actuator1"sv,
        "Actuator2"sv,
        "Cpu1"sv,
        "Cpu2"sv
    };
    
};


int main()
{
    Abc abc;
    
    std::cout << abc.SomeValues[3];

    return 0;
}

Solution

  • You need using namespace std::literals;, which is ok, unlike using namespace std;.

    See also this question on here StackOverflow, and, most importantly, this item from the C++ Core Guidelines.