Hi,
I think your question is a bit vague.
You have:
bool has() const { return get().length(); }
string& get() { /* huge code here */ return s; }
... and need has()
to be const
.
I can think of three ways to get around this, depending on what you're actually trying to do:
The cleanest option would be for has
to only use const
code. If some of your /* huge code here */
code non-const but doesn't actually change the logical value of the class (like computing a cached internal value) consider using mutable
on the data involved.
If the /* huge code here */
part is non-const by nature, consider refactoring it into a different function and calling it separately:
using namespace std;
class A {
public:
bool has() const { return get().length(); }
const string& get() const { return s; }
void computestuff() { /* huge code here */ }
private:
string s;
};
A instance;
// old client code:
// string s = instance.get();
//
// new code:
instance.computestuff(); // non-const call
instance.get(); // const call
instance.has(); // const call
Ultimately, you can also cast the const-ness away (but keep in mind that the need to do so is almost always a sign of bad design/need to refactor):
class A {
public:
bool has() const { return const_cast<A*>(this)->get().length(); }
string& get() { /* huge code here */ return s; }
private:
string s;
};