Boost logo

Boost :

From: Gennadiy E. Rozental (rogeeff_at_[hidden])
Date: 2001-08-16 20:25:28

Depends what you want.

In general you need to implement result type generator:

tempalte<typename T1, typename T2>
struct mult_result_type;

then result type for operator* would look like:
    matrix<mult_result_type<L,R> >::type

In simple case if you need to handle finite set of types you could
just provide full specializations for all cases, for example

struct mult_result_type<double,int> {
    typedef double type;

or you can provide partial specializations (if your compiler support

tempalte<typename T2>
struct mult_result_type<double,T2> {
    typedef double type;

Later on you can add specialization for user-defined types.
If you wish also provide an ability for the user to optionally
specify the result type you can write something like this:

template <class L, class R,class LR = void>
matrix<mult_result_type<LR> > operator*(const matrix<L>& lhs, const
matrix<R>& rhs)
   // return the product


tempalte<typename R, typename T1, typename T2>
struct mult_result_type {
    typedef R type;

tempalte<typename T1, typename T2>
struct mult_result_type<void,T1,T2> {
    typedef mult_result_type_impl<T1,T2>::type type;

here mult_result_type_impl is defined like mult_result_type before

Also you can try to use type_traits + template metaprogramming IF,
but it seams that it will be less flexible, example:

tempalte<typename T1, typename T2>
struct mult_result_type<void,T1,T2> {
    typedef IF< is_float<T1>::value || is_float<T2>::value, double,
int> type;

I do not know the way to automatically deduce result type in general
case. Does anybody know?

Hope it helps.


--- In boost_at_y..., "Ralf W. Grosse-Kunstleve" <rwgk_at_y...> wrote:
> I am thinking about implementing a "small matrix" library for
> 2-dimensional arrays. (This would be similar to boost::array,
> i.e. the small matrices will usually live on the stack to avoid
> the dynamic memory allocation overhead.)
> One requirement is to have operators for *heterogeneous*
> arithmetic operations, e.g. multiplication. E.g. something
> like:
> template <class LR, class L, class R>
> matrix<LR> operator*(const matrix<L>& lhs, const matrix<R>& rhs)
> {
> // return the product
> }
> Is there a mechanism in C++ to define a table for the result type LR
> depending on the types of L and R? For example, if L=int and R=int,
> the result type LR=int, but for L=double and R=int the result type
> should be LR=double, etc.
> Thanks!
> Ralf
> __________________________________________________
> Do You Yahoo!?
> Make international calls for as low as $.04/minute with Yahoo!

Boost list run by bdawes at, gregod at, cpdaniel at, john at