Re: null assignment in a template
I find it hard to believe that there isn't a clever way to solve this using
type traits, partial specialization, and/or policy templates.
Seems like there must be some way to force the compiler to convert the p = v
to p = typed_wrapper(v) which then can control operator = to do the right
thing depending on the actual value v;
I mean, you can use Int2Type<value> to make a type from an integral value,
and NULL is certainly an integral value, and then you can use partial
specialization to create the generic case for all non-null Int2Type's which
error, and the one specialization for NULL to generate a type-cast
implementation which allows assignment.
This has the advantage of forcing the caller to only use int where the int
is a constant (otherwise the compiler will complain that it cannot
instantiate a template type from a runtime variable).
I just can't quite get from the above general idea to something concrete.
Please, there must be someone out there who is into the whole template
programming thing who is familiar with type traits, partial specialization,
and policies that could make this work, neh? Or failing that, to explain
why this is truly impossible and not merely more difficult than my current
skill-level allows for.
Again, thanks for the input.
Steve
"Alex Blekhman" <xfkt@oohay.moc> wrote in message
news:%23Nr$%23uhnHHA.4188@TK2MSFTNGP02.phx.gbl...
Steve Wolf wrote:
What I Really Want(tm) is to be able to have m_pWidget = NULL evaluate to
a valid expression, and m_pWidget =
<any-other-integer-or-other-non-convertible-type> to error with "no
conversion from <type> to Widget*".
You don't have much choice other than `operator =(int)'. However, you can
check operator's parameter and throw if it isn't NULL:
T* & operator =(T* p)
{
m_value = p;
...
return m_value;
}
T* & operator =(int null)
{
if(null != 0)
{
throw "Invalid assignment.";
}
return operator=(reinterpret_cast<T*>(NULL));
}