home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!haven.umd.edu!darwin.sura.net!bogus.sura.net!howland.reston.ans.net!usc!cs.utexas.edu!geraldo.cc.utexas.edu!emx.cc.utexas.edu!not-for-mail
- From: jamshid@emx.cc.utexas.edu (Jamshid Afshar)
- Newsgroups: comp.lang.c++
- Subject: Re: template constructor specialization (question)
- Date: 12 Jan 1993 15:27:00 -0600
- Organization: The University of Texas at Austin, Austin, Texas
- Lines: 46
- Message-ID: <1ivd34INNdaa@emx.cc.utexas.edu>
- References: <DSCHIEB.93Jan5130012@muse.cv.nrao.edu>
- Reply-To: jamshid@emx.utexas.edu
- NNTP-Posting-Host: emx.cc.utexas.edu
- Summary: a specialization can't itself be a template; suggestions?
-
- In article <DSCHIEB.93Jan5130012@muse.cv.nrao.edu> dschieb@muse.cv.nrao.edu (Darrell Schiebel) writes:
- > template<class t> class id {
- > id();}
- > template<class t> class templ {};
- >
- >And now I want to write a specialized constructor for "id":
- >
- > template<class t> inline id<templ<t> >::id() {};
- >
- >What is the correct syntax for this?? I want a constructor which will be
- >called for any instantiation of "templ".
-
- Unfortunately I don't think there is a solution. A specialization
- cannot itself be a template. You may only write specializations for
- specific instances of 'templ'.
-
- inline id<templ<Foo> >::id() {}
- inline id<templ<Bar> >::id() {}
-
- I ran into this same problem when I tried to use templates to decrease
- the number of overloaded operators I write for my classes. I wrote a
- operator '+' template function which assumes the class defines
- operator '+=':
-
- template<class T>
- T operator+(const T& a, const T& b) { T r(c); c+=b; return c; }
-
- While this works for many classes and saves lots of typing, some
- classes either have different addition rules or addition can be
- implemented more efficiently than the above code. Unfortunately
- the following doesn't work:
-
- template<class T>
- T operator+(const Matrix<T>& a, const Matrix<T>& b)
- { /*...*/ }
-
- Matrix<double> x,y,z;
- z = x+y; // error: ambigous (T==Matrix<double> or T==double?)
-
- Allowing this would require some kind of template type overloading
- rules. Has anyone already thought this through? Is it possible to
- come up with general rules which would choose the latter operator+()?
-
- Jamshid Afshar
- jamshid@emx.utexas.edu
-
-