I just happened to run into a problem and I can't find a good solution other than a const_cast. The code below is just an example that illustrates my problem.
Assume the function prototype void OutputObjExistence(const ObjTest& theObj); cannot change, although the code inside can. Also assume that the set must be defined as std::set<ObjTest*> theSet;
The question is how can I do this? The currently shown way leads to a compile error (error C2664: cannot convert parameter 1 from 'const class ObjTest *' to 'class ObjTest *const & ') because it is attempting to use the parameter which is const to find the address in the set of non-const pointers.
Code:
#include <iostream>
#include <set>
class ObjTest { };
std::set<ObjTest*> theSet;
void OutputObjExistence(const ObjTest& theObj);
bool FindThisObjTest(const ObjTest& theObj);
int main()
{
ObjTest savedObjTest;
// Insert some new pointers and the saved one above.
theSet.insert(new ObjTest);
theSet.insert(new ObjTest);
theSet.insert(&savedObjTest);
theSet.insert(new ObjTest);
// Call something needing a const reference.
OutputObjExistence(savedObjTest);
// Clean up memory.
std::set<ObjTest*>::iterator iterObj = theSet.begin();
std::set<ObjTest*>::iterator iterEnd = theSet.end();
for (; iterObj != iterEnd; ++iterObj)
{
if (*iterObj != &savedObjTest)
delete *iterObj;
}
return 0;
}
// Parameter must be const reference here.
void OutputObjExistence(const ObjTest& theObj)
{
// Pass the reference to the Find method.
if (FindThisObjTest(theObj))
std::cout << "Found." << std::endl;
else
std::cout << "Not found." << std::endl;
}
// Don't care what the parameter is, but it must work.
bool FindThisObjTest(const ObjTest& theObj)
{
return theSet.find(&theObj) != theSet.end(); // Compiler error.
}