c++ - 成员的返回类型中未定义模板占位符,仍然可以正常工作吗?

标签 c++ c++11

在下面的代码片段中,我在赋值运算符 (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/

相关文章:

c++ - 与 Boost 的正则表达式区分大小写的部分匹配

c++ - 非阻塞套接字上的 select()、recv() 和 EWOULDBLOCK

c++ - 如何将具有派生参数的函数转换为具有基本参数的函数?

c++ - VS2015编译报错C2679 :

c++ - 用简单的英语理解MPI_Allgatherv

c++ - C2143 类型的错误 - 在 ',' 之前缺少 '<'

C++ 单例实例禁用重新调用

c++ - 从可变类型列表中获取最大的类型

c++ - 那是 C++ 编译器错误吗?

c++ - 如何正确处理光线追踪中的折射