Re: an "optional const"
..rhavin grobert wrote:
hello;-)
i frequently need the following construction:
ReturnParam ? Function() ?
A 'const' in the return type does not matter. The difference, however,
is sometimes like this:
ReturnType Function() const
vs
ReturnType& Function()
Therefore, it's not "const" versus "non-const" in the return value type,
it's a "temporary object" versus "reference" or
ReturnType const& Function() const
vs
ReturnType & Function()
, i.e. the 'const' in the return type is not where you show it.
{
/...do something.../
someType var ? = something;
/...do something.../
return something;
}
where ? may be 'const' or nothing. So, if the function is called as a
member function of a constant object, it needs exactly the same code
as its non-const sister, but with some additional 'const' somewhere in
the fuction.
To reduce code-doubling, it would be very nice to have some "optional
const", eg. something that the compiler automatically removes if the
fn is called on an non-const object and translates to 'const' if the
object is constant.
As i cant think of any possibility that this would break existing
code, and furthermore think it should be easy to implement.
So i'd like to know if someone sees any reason to not propose an
"optional const", and - just by the way ;-) - where i could to it...
AFAIK, folks who are sure that the 'do something' parts in those two
functions do not differ at all, simply write a const version and in the
non-const version do the const_cast in and out:
ReturnType const& Function() const
{
/* do something */
}
ReturnType& Function()
{
return const_cast<ReturnType&>(
const_cast<ThisClass const&>(*this).Function()
);
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask