Re: Propogating constness through a const member
Crosbie Fitch wrote:
Below is a compilable (on MS VS 2003) bit of code with a wee little problem.
It does not compile on Comeau because that only permits an anonymous union
to contain a single const member (all const members must be initialised,
only one member of a union can be initialised). Let's ignore that little
problemette.
Somehow I need a different member function of Item being called depending
upon whether it has been accessed via a const or non-const containing
object. Compile time detection would be preferable, but run-time is also
acceptable.
Is there some highly peculiar template malarky that can propogate the
correct constness (without increasing overhead)?
Whoever solves this has effectively enabled zero-overhead properties to
enter the C++ language (payload incurring properties are already doable).
This problem may also be solved by finding some other way to prevent the
default assign-copy operator from being called.
#include <iostream>
struct Data
{ int data[2];
void Init(int a=0,int b=0) { data[0]=a; data[1]=b; }
static Data New(int a=0,int b=0) { Data d; d.Init(a,b); return d; }
};
template <int ITEM>
class Item: private Data
{ Item& Assign(int i) { data[ITEM]=i; return *this; }
public:
operator int() const { return data[ITEM]; }
const Item& operator=(int i) const { const_cast<Item*>(this)->Assign(i);
return *this; }
};
Declaring the assignment operator a const method of the class template
"Item" makes the undesirable behavior (that is, assigning a value to a
const Item object) legal. So removing the "const" from the declaration
of operator=() will solve the problem - because assignment then will be
a legal operation for non-const Item objects only.
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]