I have the following code:
#include <string_view>
class Foo
{
public:
Foo(std::string_view) {}
};
When I do this, everything compiles fine (using clang v8, C++17):
Foo f("testing");
However, if I use copy initialization it fails:
Foo f = "testing";
Diagnostic:
prog.cc:15:9: error: no viable conversion from 'const char [8]' to 'Foo'
Foo f = "testing";
^ ~~~~~~~~~
prog.cc:7:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'const char [8]' to 'const Foo &' for 1st argument
class Foo
^
prog.cc:7:7: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'const char [8]' to 'Foo &&' for 1st argument
class Foo
^
prog.cc:10:5: note: candidate constructor not viable: no known conversion from 'const char [8]' to 'std::string_view' (aka 'basic_string_view<char>') for 1st argument
Foo(std::string_view) {}
^
1 error generated.
Looking at the constructors for string_view, I don't see any overloads that take char const[]
, is that maybe the issue? I realize I could use "testing"sv
to solve this but I feel like the string literal case should work as well.
Why doesn't the copy initialization case work? How can I make it work with string literals?