home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!snorkelwacker.mit.edu!ai-lab!life.ai.mit.edu!tmb
- From: tmb@arolla.idiap.ch (Thomas M. Breuel)
- Newsgroups: comp.lang.c++
- Subject: Re: Template classes and overloaded binary operators on differing types
- Date: 20 Nov 92 17:35:58
- Organization: IDIAP (Institut Dalle Molle d'Intelligence Artificielle
- Perceptive)
- Lines: 62
- Message-ID: <TMB.92Nov20173558@arolla.idiap.ch>
- References: <1egmvkINNi35@emory.mathcs.emory.edu>
- Reply-To: tmb@idiap.ch
- NNTP-Posting-Host: arolla.idiap.ch
- In-reply-to: sb@next.neuro.emory.edu's message of 19 Nov 1992 18:38:44 GMT
-
- Can someone please comment on the following problem and suggest the
- "best" way to solve it.
-
- Say I have a template class that implements a VECTOR type and binary
- operators like addition and subtraction. All of the binary operators are
- currently implemented as template friend functions which accept two
- vectors of the same type. For example, I have this :
-
-
- VECTOR<int> ivec1(3),ivec2(3),ivec3(3); // 3 is vector size
-
- ivec3 = ivec1 + ivec2;
-
- My question is, how can I extend this so that I can add vectors of
- differing types ? e.g.,
-
- VECTOR<int> ivec1(3);
- VECTOR<double> dvec1(3),dvec2(3);
-
- dvec2 = ivec1 + dvec1;
-
- What is a good way to implement this ?
-
- There are several methods:
-
- (1) define a conversion operator:
-
- template <class T>
- struct VECTOR {
- ...
- operator VECTOR<int> { ... }
- operator VECTOR<double> { ... }
- ...
- };
-
- (2) write an explicit conversion function (can be a template
- function for convenience):
-
- template <class T>
- VECTOR<double> as_double_VECTOR(VECTOR<T> &v) {
- ...
- };
-
- (3) overload operator+:
-
- VECTOR<double> operator+(VECTOR<int> &v1,VECTOR<double> &v2) {...}
-
- (4) overload operator+ with a template:
-
- template <class X,class Y>
- VECTOR<X> operator+(VECTOR<X> &v1,VECTOR<Y> &v2) {...}
-
- Personally, I'd use (and I have used) (2). Method (1) doesn't work
- with GNU C++. Method (3) is usually considered the "most efficient",
- but in terms of runtime, the difference is usually insignificant; the
- main difference is that it requires less space than conversion
- methods, but it requires a whole lot more code. Method (4) may look
- appealing, but the return type is wrong (sometimes you want VECTOR<X>,
- sometimes VECTOR<Y>), and there is no way of fixing this in C++.
-
- Thomas.
-
-