Boost logo

Boost :

From: George A. Heintzelman (georgeh_at_[hidden])
Date: 2001-01-12 16:05:17


From: "Stephen Silver" <boost_at_[hidden]>
> Jens Maurer wrote:
>
> > "Moore, Paul" wrote:
> > > From: "Stephen Silver" <boost_at_[hidden]>
> > > > template <class T> rational(T n) : num(), den(1) { num = n; }
>
> 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.

This is where you need an implicit_cast template:

template <class ToClass, class FromClass>
ToClass implicit_cast(const FromClass &casted_object)
        { return casted_object; }

which will not compile unless there is an implicit conversion from
FromClass to ToClass. Then the constructor becomes:

template <class T> rational(T n) :
        num(boost::implicit_cast<IntType>(n)),
        den(IntType(1)) {} // Or whatever you finally decide to use for 1.

I seem to remember some discussion about exactly this sort of need, and
had thought that it was in the BCL, but it doesn't seem to be. Perhaps
this is an example which suggests it needs to be added?

(BTW: My first post to boost, after watching for a while. Many thanks
to all you guys for providing such a great resource to the C++
programming community!)

George Heintzelman
georgeh_at_[hidden]


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