在下面的代码片段中,我在赋值运算符 (operator=) 的返回类型中省略了模板参数占位符。在我指定或不指定模板参数的两种情况下,代码都运行良好,只是想知道为什么?
谢谢
#include <iostream>
using std::cout; using std::endl;
class Ref
{
int _ref_counter;
public:
Ref() : _ref_counter(0) {}
void upRef() { _ref_counter++; }
int downRef() { return --_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 the existing smartpointer info
if(0 == _ref->downRef())
{
delete _ptr;
delete _ref;
}
_ptr = sp._ptr;
_ref = sp._ref;
_ref->upRef();
}
return *this;
}
~SmartPointer()
{
if(0 == _ref->downRef())
{
delete _ptr;
delete _ref;
}
}
T1& operator* () { return *_ptr; }
T1* operator-> () { return _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();
}
最佳答案
来自标准 [n3690: 14.6.1/1]:
Like normal (non-template) classes, class templates have an injected-class-name (Clause 9). The injected class-name can be used as a template-name or a type-name. When it is used with a template-argument-list, as a template-argument for a template template-parameter, or as the final identifier in the elaborated-type specifier of a friend class template declaration, it refers to the class template itself. Otherwise, it is equivalent to the template-name followed by the template-parameters of the class template enclosed in <>.
关于c++ - 成员的返回类型中未定义模板占位符,仍然可以正常工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26591103/