🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #3680

Re: Problem with new in templates...

#3680
From: Fergus Henderson
Date: Fri, 15 Mar 1996 02:02
53 lines
2309 bytes
adamnash@cs.stanford.edu (Adam Nash) writes:

>[...] for semantic reasons, the template assumes that DATA is a pointer type.
[...]
>template <class DATA>
>void GIDTable::ReadFromStream(LStream *inStream)
>{
>   DATA data;
>
>   ...
>
>   data = new DATA;
>   (*data).ReadFromStream(inStream);
>
>   ...
>}
>
>
>The problem occurs on the second line.  data is of type DATA, so you
>really want to allocate a new (*DATA).  IE, if DATA is a CBar *, then data
>is a CBar *,
>so we want it to say: data = new CBar;
>
>How can I do this, only knowing the pointer type?

You can use a partial template specialization:

	template <class T> struct dereference {};
	template <class T> struct dereference <T*> {
		typedef T type;
	};
		
Then just write

	data = new dereference<Data>::type;

(I note in passing that this would of course be less obfuscated if C++
supported template typedefs...)

Now, the reason that all of this belongs in comp.std.c++ not comp.lang.c++
is that the above code is valid according to the standard, but is highly
unlikely to work with your favourite C++ compiler.  Partial specialization
is a relatively new feature, and few C++ compilers support it yet.

--
Fergus Henderson             	WWW: http://www.cs.mu.oz.au/~fjh
fjh@cs.mu.oz.au              	PGP: finger fjh@128.250.37.3
---
[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]
Technical Details
Message-ID: <4iaisq$2ai@mulga.cs.mu.OZ.AU>
Path: arc1-ca.pugleaf.net!in2.uu.net!bounce-back
References: <adamnash-1303962301470001@gel.stanford.edu>

Show Full Headers
Complete Article Headers
From: fjh@mundook.cs.mu.OZ.AU (Fergus Henderson)
Message-ID: <4iaisq$2ai@mulga.cs.mu.OZ.AU>
X-Original-Date: 15 Mar 1996 01:58:50 GMT
Path: arc1-ca.pugleaf.net!in2.uu.net!bounce-back
Date: 15 Mar 96 02:02:37 GMT
Approved: fjh@cs.mu.oz.au
Newsgroups: comp.std.c++
Subject: Re: Problem with new in templates...
Organization: Comp Sci, University of Melbourne
References: <adamnash-1303962301470001@gel.stanford.edu>
X-Auth: PGPMoose V1.1 PGP comp.std.c++
 iQBFAgUBMUjPxeEDnX0m9pzZAQGtmQF/bogBIvH/bV09KftATi+3xUYYtSFGIzLJ
 j6695NZ+LXJ5eEUBS1qMvMiXqD2LvnCi
 =7unq