Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare boost::string_ref to std::string

I'm trying to make boost::string_ref working as I want to, but I'm facing a problem right now - following code does not compile:

 #include <boost/utility/string_ref.hpp> 
 #include <iostream> 
 #include <string> 

 using namespace std;

int main() {
   string test = "test";
   boost::string_ref rtest(test);
   cout << (rtest == "test")<<endl;
}

and the gcc throws 30kB error log, starting with

source.cpp: In function 'int main()':
source.cpp:10:19: error: no match for 'operator==' (operand types are 'boost::string_ref {aka boost::basic_string_ref<char, std::char_traits<char> >}' and 'const char [5]')
    cout << (rtest == "test")<<endl;
                   ^

How to compare boost::string_ref to std::string?

like image 553
Wojciech Danilo Avatar asked Sep 28 '26 23:09

Wojciech Danilo


2 Answers

Honestly, I'd just avoid using string_ref entirely until it matures. The fact that you can't compare a string_ref to a std::string or a const char * out of the box should set alarm bells ringing (looks like they forgot to write a bunch of comparison operators), and worse, it doesn't look like the library received sufficient testing (e.g. bug 8067!).

like image 121
Nick Hutchinson Avatar answered Oct 01 '26 16:10

Nick Hutchinson


Just make a string_ref out of the string. They are very cheap to construct. Though against a string literal, you may want to include the length. Otherwise it's going to iterate once to find the end of the string, and then iterate again to compare them. Just make sure that if you change the string, you keep the count up to date.

cout << (rtest == boost::string_ref("test",4)) << endl;

With a std::string, you don't need to worry about the count, because string_ref will just call the size() member function, which is also very cheap.

like image 38
Benjamin Lindley Avatar answered Oct 01 '26 16:10

Benjamin Lindley