Let me say we have a simple programming task. But for the sake of clarity I start with few code samples. First of all we written a some kind of data container class but for the purposes of task no matter what the class is. We just need it to behave const-correct.
class DataComponent {
public:
const std::string& getCaption() const {
return caption;
}
void setCaption(const std::string& s) {
caption = s;
}
private:
std::string caption;
};
Then let us assume we've got a generic class that behaves like facade over arbitrary incapsulated class instance. Say we overloaded member access operator (->
).
template <typename T> class Component {
public:
Component() { instance = new T(); }
...
const T* operator-> () const {
return instance;
}
T* operator-> () {
// but there might be additional magic
return instance;
}
private:
T *instance;
};
At this point I should say how I want this to work:
- if we're calling non-const member functions of underlying class through member access operator (
component->setCaption("foo")
) compilier treats non-constT* operator-> ()
as the best choice. - otherwise if we are trying to call const member functions of underlying class same way (
component->getCaption()
) compiliers selectsconst T* operator-> () const
on the other hand.
This code sample above won't work this way so I'm curious about possibility to give compiler a behavior like that I have mentioned. Any propositions.
EDIT: Let our member access operator overloaded this way:
const T* operator-> () const { return instance; }
T* operator-> () {
cout << "something going change" << endl;
return instance;
}
And let us have a variable Component<DataComponent> c
somewhere. Then on the call to c->getCaption()
stdout should remain silent but on the call to c->setCaption("foo")
stdout should warn us that something is going to change. VS 2010 compilier makes stdout warn us on each of these calls.
I understand that such semantics suppose that c
behaves as const and non-const at the same time. But curiousity is still in my mind.