1

As per the C++17 book from "Nicolai M. Josuttis" the following code should compile.

#include <string_view>
#include <string>
int main()
{
        std::string_view sv1 = "hello";
        std::string_view sv2 = "world";
        auto s = std::string(sv1) + sv2;
}

I get the following error (edited for clarity)

    test.cpp: In function ‘int main()’:
    test.cpp:7:28: error: no match for ‘operator+’ (operand types are ‘std::string’ and ‘std::string_view’)
        7 |  auto s = std::string(sv1) + sv2;
          |                ~~~~~~~~~~~ ^ ~~~
          |                |             |
          |                |             std::string_view {aka std::basic_string_view<char>}
          |                std::string {aka std::basic_string<char>}
    In file included from /usr/lib/gcc/x86_64-pc-cygwin/9.3.0/include/c++/bits/stl_algobase.h:67,
                     from /usr/lib/gcc/x86_64-pc-cygwin/9.3.0/include/c++/bits/char_traits.h:39,
                     from /usr/lib/gcc/x86_64-pc-cygwin/9.3.0/include/c++/string_view:42,
                     from test.cpp:1:
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 1
    Which version of GCC 9 exactly, and with what compiler options? What is the exact example in the book that says this should work, and why does it think so? [cppreference](https://en.cppreference.com/w/cpp/string/basic_string/operator%2B) does not define any such overload of `operator+`. Books can be wrong! Or readers can paraphrase them wrong ;-) – underscore_d Jun 15 '20 at 14:52
  • @underscore_d is right, see more about char* + char* in this https://stackoverflow.com/questions/23936246/error-invalid-operands-of-types-const-char-35-and-const-char-2-to-binar – dejoma Jun 15 '20 at 14:57
  • @dejoma This is about `std::string_view`, not `char*`. – underscore_d Jun 15 '20 at 15:11
  • string_view is a struct = { char*, size_t } – dejoma Jun 15 '20 at 15:22
  • @dejoma Sure, but that doesn't really matter at all! As soon as it's not a `char*`, one could've provided an `operator+()` for it. The question is why the Standard didn't do so. – underscore_d Jun 15 '20 at 16:06
  • 1
    I am using gcc 9.3.0. The exact phrase from the book is this "Note that there is no support for operator+. Thus: std::string_view sv1 = "hello"; std::string_view sv2 = "world"; auto s1 = sv1 + sv2; //ERROR One of the operands has to be a string: auto s2 = std::string(sv1) + sv2; // OK Note that there is no implicit conversion to a string because this is an expensive operation since it might allocate memory. Therefore, only the explicit conversion is possible – Amit Mishra Jun 16 '20 at 07:17

0 Answers0