Glib::ustring not compatible with std::replace from <algorithm>
I'm not sure if this is even supposed to work, but I recently stumbled across it when trying to perform the "trivial" task of replacing all underscores in a Glib::ustring
with spaces.
Consider the following example program:
#include <algorithm>
#include <iostream>
#include <glibmm.h>
#define TEST_STRING "a_sentence_with_underscores";
int main (int argc, char **argv)
{
std::string s = TEST_STRING;
std::replace(s.begin(), s.end(), '_', ' ');
std::cout << s << std::endl;
Glib::ustring u = TEST_STRING;
std::replace(u.begin(), u.end(), '_', ' '); // does not compile
std::cout << u << std::endl;
return 0;
}
While this works just fine for std::string
it does not compile for Glib::ustring
.
Compiler error:
$ g++ `pkg-config --cflags glibmm-2.4` replace.cpp -o replace.exe `pkg-config --libs glibmm-2.4` && ./replace.exe
In file included from C:/msys64/mingw64/include/c++/9.1.0/algorithm:62,
from replace.cpp:4:
C:/msys64/mingw64/include/c++/9.1.0/bits/stl_algo.h: In instantiation of 'void std::replace(_FIter, _FIter, const _Tp&, const _Tp&) [with _FIter = Glib::ustring_Iterator<__gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> > >; _Tp = char]':
replace.cpp:18:46: required from here
C:/msys64/mingw64/include/c++/9.1.0/bits/stl_algo.h:4360:13: error: lvalue required as left operand of assignment
4360 | *__first = __new_value;
| ~~~~~~~~~^~~~~~~~~~~~~
Because of this I ended up implementing it a lot less elegant with a while loop, using Glib::ustring::find
to locate the underscores and replacing them one by one.
Edited by Patrick Storz