Topic: a template question


Author: rmartin@rcmcon.com (Robert Martin)
Date: Fri, 17 Sep 1993 14:51:37 GMT
Raw View
venkat@lgc.com (Venkat Viswanathan) writes:

>Is it possible to write a function which does the following :

>Given
>. a type V which supports the operators = and <
>. a type T which has a method x() which returns something of
>  type V, that is V T::x()
>define a function which computes the minimum.

>template< class V, class T<V> >
                    ^^^^^^^^^^    Odd Syntax.  See below.
>V computeXmin( const T<V>* arr, int n )
>{
> // assume n > 0
> V min = arr[0].x() ;
> for ( int i = 1 ; i < n ; i++ )
>  if ( arr[i].x() < min ) min = arr[i].x() ;
> return min ;
>}

The template mechanism is not strongly typed.  It does not care what
kind of class is used in its arguments as long as that class has the
appropriate  interface.  In your case, all you need is a class which
has an x() method which returns a V or something that can be converted
to a V.  This may in fact be a T<V>, or it may be something else.  The
template processor does not care.

Consider this syntax.

>template< class V, class A >
>void computeXmin( const A* arr, int n, V& v)
>{
> // assume n > 0
> V min = arr[0].x() ;
> for ( int i = 1 ; i < n ; i++ )
>  if ( arr[i].x() < min ) min = arr[i].x() ;
> v=min;
>}

You can call this as follows:

T<V> array[10];
V v;

computeXmin(array, 10, v);

-------

Returning the value V is problematic since the signature of the
function must be wholly specified by its arguments.  Thus, the
function must return its V through a reference argument rather than as
a return variable.


--
Robert Martin       | Design Consulting   | Training courses offered:
Object Mentor Assoc.| rmartin@rcmcon.com  |   Object Oriented Analysis
2080 Cranbrook Rd.  | Tel: (708) 918-1004 |   Object Oriented Design
Green Oaks IL 60048 | Fax: (708) 918-1023 |   C++




Author: grumpy@cbnewse.cb.att.com (Paul J Lucas)
Date: Sun, 19 Sep 1993 13:33:55 GMT
Raw View


Author: venkat@lgc.com (Venkat Viswanathan)
Date: Thu, 16 Sep 1993 20:43:34 GMT
Raw View
Is it possible to write a function which does the following :

Given
. a type V which supports the operators = and <
. a type T which has a method x() which returns something of
  type V, that is V T::x()
define a function which computes the minimum.

e.g. I have 2 template classes

template<V> class Point2d
{
public:
 V x() ;
 V y() ;
}

and

template<V> class Point3d
{
public:
 V x() ;
 V y() ;
 V z() ;
}

and I'd like to use the same function to compute the minimum x
co-ordinate and I cannot have a common base class for
Point2d and Point3d.

Is something along these lines legal? Is so, could someone tell me
what the syntax looks like?

template< class V, class T<V> >
V computeXmin( const T<V>* arr, int n )
{
 // assume n > 0
 V min = arr[0].x() ;
 for ( int i = 1 ; i < n ; i++ )
  if ( arr[i].x() < min ) min = arr[i].x() ;
 return min ;
}
--
--
Venkat Viswanathan - venkat@lgc.com - (713) 560-1201