const problem
MS Developer Studio 7.
I ran in to this experimenting with STL sets the first time. Had it not
been for sample code on page 295 of The C++ Standard Library by Nicolai
Josuttis, I nver would have solved it. The compiler error just didn't give
me the help I needed to figure out what was wrong. Here is the smallest
code snippet I can craft that produces the error:
#include <set>
using namespace std;
struct MyElem {
int value;
};
struct MyCompare
{
bool operator() ( const MyElem& elem1, const MyElem& elem2 )
{
return( elem1.value < elem2.value );
}
};
void main()
{
MyElem myElem;
int count;
set<MyElem, MyCompare> MySet;
count = MySet.erase( myElem );
}
That code produces this cryptic compile time error message
c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\xtree(992) :
error C3848: expression having type 'const MyCompare' would lose some
const-volatile qualifiers in order to call 'bool MyCompare::operator
()(const MyElem &,const MyElem &)'
c:\Program Files\Microsoft Visual Studio .NET
2003\Vc7\include\xtree(987) : while compiling class-template member function
'std::_Tree<_Traits>::_Nodeptr std::_Tree<_Traits>::_Lbound(const
std::_Tree<_Traits>::key_type &) const'
with
[
_Traits=std::_Tset_traits<MyElem,MyCompare,std::allocator<MyElem>,false>
]
c:\Program Files\Microsoft Visual Studio .NET
2003\Vc7\include\set(57) : see reference to class template instantiation
'std::_Tree<_Traits>' being compiled
with
[
_Traits=std::_Tset_traits<MyElem,MyCompare,std::allocator<MyElem>,false>
]
h:\BAC\win32\misc2\misc2.cpp(120) : see reference to class template
instantiation 'std::set<_Kty,_Pr>' being compiled
with
[
_Kty=MyElem,
_Pr=MyCompare
]
The error doesn't point to my code, but rather to STL code. I finally
figured out what the problem was by trial and error and comparing to that
book example I mentioned. It turned out that this line:
bool operator() ( const MyElem& elem1, const MyElem& elem2 )
should have a 3rd "const" on it at the end as in:
bool operator() ( const MyElem& elem1, const MyElem& elem2 ) const
Adding that last const completely eliminated the compiler errors.
I know what the first 2 const's do. My question is what does the 3rd const
mean and why is it required in this case?
Thanks,
Bruce.