I'm working on an MFC application using VS 2012. In this application, I want to sanitize a container of CString objects by using the Trim() member function. First, I used a std::vector as container, as shown in the following MCVE:
#define _AFXDLL // CString
#include <afx.h> // CString
#include <vector>
int main()
{
std::vector<CString> v;
v.push_back(_T("Test"));
v.begin()->Trim();
return 0;
}
This compiles and works as expected. Then, I wanted to replace the std::vector by a std::set. Therefore, I included #include <set> instead of #include <vector> and changed main() as follows:
int main()
{
std::set<CString> s;
s.insert(_T("Test"));
s.begin()->Trim();
return 0;
}
However, this gives me the following compile error on the s.begin()->Trim(); line:
error C2663: 'ATL::CStringT>>::Trim' : 3 overloads have no legal conversion for 'this' pointer
The documentation of the error basically says:
[...] This error can be caused by invoking a non-const member function on a const object. [...]
However, compared to the vector version, I didn't add any const qualifier. Also, std::set::begin() provides a non-const iterator, just as std::vector::begin() does. I found similar questions on error C2663, for example, this one. But in most of these cases, someone tried to modify a member from a const function, which is not the case in my code.
Why can't I use Trim() on CString objects in a std::set and how can I fix this problem?