I am using an external C++ library that lacks const-correctness. Lets say I am working with objects of the following class:
// Library.h
namespace Library {
class Message {
public:
std::string getData() {
return data_;
}
private:
std::string data_;
};
} // namespace Library
Note that getData()
returns a copy, thus a call to the method does not change the Message
object and it should be const
. However, the vendor decided it's not.
On my side of the code, const-correctness is important and the Message
is to be used in a function like so:
// MyApplication.cpp
template<class T>
void handleMessage(const T& msg) {
std::string content = msg.getData();
// interprete and process content ...
}
Is there a way to achieve this? In other words, how to work around the error: passing 'const Library::Message' as 'this' argument discards qualifiers
error without changing the signature of the handleMessage
function?
You could also use wrapper with mutable member variable like:
[live demo]
Edit:
To force const correctness you could save once retrieved data from the message e.g.:
[live demo]