Tuesday, 15 February 2011

c++ - Template placeholder not defined in return type of member, still works fine? -



c++ - Template placeholder not defined in return type of member, still works fine? -

in next snippet, omitted template param placeholder in homecoming type of assignment operator (operator=). in both cases have specified template parameter or not, code runs fine, wondering why?

thanks

#include <iostream> using std::cout; using std::endl; class ref { int _ref_counter; public: ref() : _ref_counter(0) {} void upref() { _ref_counter++; } int downref() { homecoming --_ref_counter; } }; template <typename t1> class smartpointer { t1* _ptr; ref *_ref; public: smartpointer() : _ptr(0) { _ref = new ref(); _ref->upref(); } smartpointer(t1* ptr): _ptr(ptr) { _ref = new ref(); _ref->upref(); } smartpointer(const smartpointer &sp): _ptr(sp._ptr), _ref(sp._ref) { { _ref->upref(); } // smartpointer<t1>& operator= (const smartpointer &sp) smartpointer& operator= (const smartpointer &sp) { //always check self assignment if(this != &sp) { //lose existing smartpointer info if(0 == _ref->downref()) { delete _ptr; delete _ref; } _ptr = sp._ptr; _ref = sp._ref; _ref->upref(); } homecoming *this; } ~smartpointer() { if(0 == _ref->downref()) { delete _ptr; delete _ref; } } t1& operator* () { homecoming *_ptr; } t1* operator-> () { homecoming _ptr; } }; class lock { public: void somefuntion() { cout << "somefunction called ! " << endl; } ~lock() { cout << "destructor lock called !" << endl; } }; int main() { smartpointer<lock> pmemlock(new lock()); pmemlock->somefuntion(); { smartpointer<lock> pmemlock1(pmemlock); } smartpointer<lock> pmemlock2; pmemlock2 = pmemlock; pmemlock2->somefuntion(); }

from standard [n3690: 14.6.1/1]:

like normal (non-template) classes, class templates have injected-class-name (clause 9). injected class-name can used template-name or type-name. when used template-argument-list, template-argument template template-parameter, or final identifier in elaborated-type specifier of friend class template declaration, refers class template itself. otherwise, equivalent template-name followed template-parameters of class template enclosed in <>.

c++ c++11

No comments:

Post a Comment