As others have stated, you cannot tell if an object was declared as const
from within a member function. You can only tell if it's being called in a const
context, which is not the same.
MOTIVATION: I want to be able to detect whether a const member function is invoked on a const object or is coming from a non-const object. The object could e.g. represent a cache and the member a view. If the cache was const, one could presumably use an optimized draw routine, whereas if the underlying data was non-const, the draw routine would need to do periodically check if the data was refreshed.
You can't tell that reliably.
struct A
{
void draw() { fut = std::async(&A::do_draw, this, false); }
void draw() const { fut = std::async(&A::do_draw, this, true); }
void update(Data&);
private:
void do_draw(bool this_is_const) const;
mutable std::future<void> fut;
};
A a;
const A& ca = a;
ca.draw(); // object will think it's const, but isn't
Data new_data = ...;
a.update(new_data); // do_draw() should recheck data, but won't
You can model it in the type system, by defining separate mutable and immutable types.
struct Base
{
virtual ~Base();
virtual void draw() const = 0;
protected:
void do_draw(bool) const;
};
struct MutableCache : Base
{
virtual void draw() const { fut = std::async(&Base::do_draw, this, false); }
void update();
};
struct ImmutableCache : Base
{
virtual void draw() const { fut = std::async(&Base::do_draw, this, true); }
// no update function defined, data cannot change!
};
Now if a cache is create as an ImmutableCache
you know it can't change, so that replaces your previous idea of a "const" object. A MutableCache
can change, so needs to check for refreshed data.