home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!stanford.edu!EE.Stanford.EDU!sierra!mcgrant
- From: mcgrant@rascals.stanford.edu (Michael C. Grant)
- Subject: Re: template member func: class X { template<class T> f(T& x) {...}}
- In-Reply-To: gs4t@virginia.edu's message of 22 Nov 92 21:03:14 GMT
- Message-ID: <MCGRANT.92Nov22175156@rascals.stanford.edu>
- Sender: usenet@EE.Stanford.EDU (Usenet)
- Organization: Information Systems Laboratory, Stanford University
- References: <mg.722310420@elan> <1992Nov22.210314.18135@murdoch.acc.Virginia.EDU>
- Date: 22 Nov 92 17:51:56
- Lines: 79
-
- In article <1992Nov22.210314.18135@murdoch.acc.Virginia.EDU>
- gs4t@virginia.edu (Gnanasekaran Swaminathan) writes:
-
- mg@elan (Michael Golan) writes:
- : Why isnt this allowed?
- :
- : class File {
- : binwrite(void *buf,size_t sz) {...} // write buf of length sz
- : public:
- : template<class T> write(T& buf) { binwrite(buf,sizeof(T)); }
- : };
- Because there is an alternate way to do the same.
- template <class T>
- class File {
- void binwrite(void* buf, int sz) {}
- public:
- void write(T* b) { binwrite(b, sizeof(T)); }
- };
- main()
- {
- File<int> f;
- int i = 0;
- f.write(i);
- }
-
- That ISN'T the same thing. What if I wanted to do this:
-
- main() {
- File* f;
- int i = 10;
- double j = 4;
- ...
- f.write(i);
- f.write(j);
- }
-
- The benefit to allowing this is that write(T& buf) could then be inlined
- for every data type. I believe a superior example is this:
-
- template <class T>
- class Matrix {
- // just guess how it's defined!
- public:
- template <T (*func)(const T&)> Matrix& apply( void ) {
- for ( register int i = 0; i < totalLength ; i++ )
- data[i] = (*func)(data[i]);
- return *this;
- }
- Matrix& apply( T (*func)(const T&) ) { ...non-templated form... }
- Matrix operator-( void ) const { return Matrix(*this).apply<&operator->(); }
- // questionable syntax?
- }
-
- Why is this useful? Because some computers have inlinable code for some
- of the standard floating-point functions such as fabs(), sqrt(), etc. So,
- I would hope and expect that a compiler could take
-
- main() {
- Matrix<double> m(50,50);
- ...
- m.apply<&fabs>();
- m.apply<&sqrt>();
- }
-
- and properly inline the code. (alternatively, I could have written an
- inlined function myself...) I've also wanted to template conversions
- from one Matrix type to another, i.e.
-
- template <class T,class U>
- Matrix<T>::Matrix( const Matrix<U>& m ) { ... }
-
- and let compiler errors and the like reject conversions that aren't
- automatic.
-
- Mike
-
- --
- -----
- "Long hair, short hair--what's the difference once the head's blowed off?" (?)
-