0

I have created the following NullTerminatedStringView class:

Why can't my NullTerminatedStringView be created from std::string without writing explicit constructor for it? As I understand, it should be able to do it automatically.

#include <string>
#include <string_view>

class NullTerminatedStringView
{
private:

    std::string_view stringView;
public:

    NullTerminatedStringView( std::string_view const stringView )
        : stringView( stringView ) { }

    operator std::string_view () const
    {
        return stringView;
    }

    const char * cStr() const
    {
        return stringView.data();
    }

    size_t size() const
    {
        return stringView.size();
    }

};

void f( NullTerminatedStringView const path ) { }
int main()
{
    std::string ss = "string";
    f( ss ); // no matching function for call to 'f'
}

You can test it here: https://godbolt.org/z/cvjbaG

cubiii
  • 359
  • 3
  • 11
  • 2
    Please post the relevant code (a [mcve]) here, don't link to an external site. – Werner Henze Mar 15 '21 at 10:23
  • 3
    Implicit conversions only perform one cast. https://en.cppreference.com/w/cpp/language/implicit_conversion – Jorge Bellon Mar 15 '21 at 10:32
  • As a side note, your code is dangerous, as `std::string_view` is not guaranteed to be null terminated. https://en.cppreference.com/w/cpp/string/basic_string_view/data – Kaldrr Mar 15 '21 at 10:57

0 Answers0