Boost logo

Boost :

From: Stephen Silver (boost_at_[hidden])
Date: 2001-01-12 15:25:51


Jens Maurer wrote:

> "Moore, Paul" wrote:
> > From: "Stephen Silver" <boost_at_[hidden]>
> > > template <class T> rational(T n) : num(), den(1) { num = n; }
> >
> > Good catch - I'll add this.
>
> Do make sure to document it right in the code. Any time I see such
> code as "default initialize + assign" in foreign code, I assume
> the code writer has not understood C++ at all.

Yes, it needs to be explained, otherwise someone might "correct" it.

> > Hmm. Overall, I agree with this, although I wonder whether there could be
> > cases where default-construct and assign is significantly slower than just
> > constructing. Seems far less likely than even the explicit constructor case,
> > though, and it's "only" performance, so I'd go with it.
>
> What about a fixed-size bigint based on a C array which needs to be
> default-initialized to 0 all over?

This is a good point. I didn't really like using the assignment, but
the alternative is to turn explicit conversions to IntType into implicit
conversions to rational<IntType>, which can't be good.

> It's ugly. It's a template implicit conversion. :-(

Yes, but I don't really see any problems with it, other than the
efficiency issue with certain bigint types. In cases where the
efficiency is a real issue, the template constructor can be by-passed
by using an explicit cast to IntType.

> For the problem at hand, it seems sufficient to have a rational
> constructor which takes an "int" (or long) only.

But then someone will use a value that doesn't fit in a long (e.g., an
unsigned long, or a larger non-standard type) and it will be converted
to an int (or a long), with the wrong result. I think all types that
are implicitly convertible to IntType ought to be implicitly convertible
to rational<IntType> as a matter of principle, and a template is the
only way to do that.

Stephen


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk