home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / lang / cplus / 19038 < prev    next >
Encoding:
Text File  |  1993-01-12  |  2.2 KB  |  60 lines

  1. 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
  2. From: jamshid@emx.cc.utexas.edu (Jamshid Afshar)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: template constructor specialization (question)
  5. Date: 12 Jan 1993 15:27:00 -0600
  6. Organization: The University of Texas at Austin, Austin, Texas
  7. Lines: 46
  8. Message-ID: <1ivd34INNdaa@emx.cc.utexas.edu>
  9. References: <DSCHIEB.93Jan5130012@muse.cv.nrao.edu>
  10. Reply-To: jamshid@emx.utexas.edu
  11. NNTP-Posting-Host: emx.cc.utexas.edu
  12. Summary: a specialization can't itself be a template; suggestions?
  13.  
  14. In article <DSCHIEB.93Jan5130012@muse.cv.nrao.edu> dschieb@muse.cv.nrao.edu (Darrell Schiebel) writes:
  15. >    template<class t> class id {
  16. >      id();}
  17. >    template<class t> class templ {};
  18. >
  19. >And now I want to write a specialized constructor for "id":
  20. >
  21. >    template<class t> inline id<templ<t> >::id() {};
  22. >
  23. >What is the correct syntax for this?? I want a constructor which will be
  24. >called for any instantiation of "templ".
  25.  
  26. Unfortunately I don't think there is a solution.  A specialization
  27. cannot itself be a template.  You may only write specializations for
  28. specific instances of 'templ'.
  29.  
  30.     inline id<templ<Foo> >::id() {}
  31.     inline id<templ<Bar> >::id() {}
  32.     
  33. I ran into this same problem when I tried to use templates to decrease
  34. the number of overloaded operators I write for my classes.  I wrote a
  35. operator '+' template function which assumes the class defines
  36. operator '+=':
  37.  
  38.     template<class T>
  39.     T operator+(const T& a, const T& b) { T r(c); c+=b; return c; }
  40.  
  41. While this works for many classes and saves lots of typing, some
  42. classes either have different addition rules or addition can be
  43. implemented more efficiently than the above code.  Unfortunately
  44. the following doesn't work:
  45.  
  46.     template<class T>
  47.     T operator+(const Matrix<T>& a, const Matrix<T>& b)
  48.     { /*...*/ }
  49.  
  50.     Matrix<double> x,y,z;
  51.     z = x+y;    // error: ambigous (T==Matrix<double> or T==double?)
  52.  
  53. Allowing this would require some kind of template type overloading
  54. rules.  Has anyone already thought this through?  Is it possible to
  55. come up with general rules which would choose the latter operator+()?
  56.  
  57. Jamshid Afshar
  58. jamshid@emx.utexas.edu
  59.  
  60.