70 likes | 145 Views
RPI Proglang Fall 2002 Group 8 Tim Kong <kongt@rpi.edu> Tina Liu <liut2@rpi.edu> Geoff Maahs <maahsg@rpi.edu> Christopher Werner <wernec2@rpi.edu> Matthew Wronka <wronkm@rpi.edu>. The Keyword template. class Memory { public: template<class T> T* get_new();
E N D
RPI Proglang Fall 2002 Group 8 Tim Kong <kongt@rpi.edu> Tina Liu <liut2@rpi.edu> Geoff Maahs <maahsg@rpi.edu> Christopher Werner <wernec2@rpi.edu> Matthew Wronka <wronkm@rpi.edu> The Keyword template
class Memory { public: template<class T> T* get_new(); template<class T> void release(T&); }; The Keyword template Sometimes a compiler needs help to determine the specialization of a function template. For some allocator m we can write: m.release(p); We need to use: m.template get_new<int>(); But we cannot write: int* p=m.get_new();
m.template get_new<int>(); 14.2 When the name of a member template specialization appears after . Or > in a postfix expression, or after :: in a qualified id that explicitly depends on a template argument (14.6.2), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a nontemplate. m.template get_new<int>();
m.release(p); How does the compiler know how to deal with m.release(p)? 14.8.2 Template arguments that can be deduced from the function arguments of a call need not be explicitly specified. m.template get_new<int>(); No arguments? Can't deduce type!
class Memory { public: template<class T> T* get_new(); template<class T> void release(T&); }; template<class Allocator> void f(Allocator& m) { int* p1=m.get_new<int>(); // error int* p2=m.template get_new<int>(); // ok } The Keyword template What is the problem on line 7?
m.template get_new<int>(); 14.2 When the name of a member template specialization appears after . Or > in a postfix expression, or after :: in a qualified id that explicitly depends on a template argument (14.6.2), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a nontemplate. m.template get_new<int>(); Not m.get_new<int>();
When do we need template? The Keyword Template • When it prevents a parsing ambiguity • Whenever the compiler cannot deduce the type • Whenever it prevents ambiguity according to the spec