c++ - 在没有模板参数的类模板中使用类名

标签 c++ templates

代码来自一本C++书籍如下:

为什么这个公共(public)成员 Link* next 没有类型名参数?

template <typename E> class Link {
private:
    static Link<E>* freelist;
public:
    E element;
    Link* next;  // this line confused me....

    Link(const E& elemval, Link* nextval = NULL)
    {
        element = elemval; next = nextval;
    }
    Link(Link* nextval = NULL) { next = nextval; }
    void* operator new(size t){
        if (freelist == NULL) return ::new Link;
        Link<E>* temp = freelist;
        freelist = freelist->next;
        return temp; // Return the link
    }
};

我觉得应该是Link<E>* next .

请告诉我它没有模板参数的原因。

最佳答案

这被称为“注入(inject)的类名”。该规则具体来自[temp.local]:

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 <>.

Within the scope of a class template specialization or partial specialization, when the injected-class-name is used as a type-name, it is equivalent to the template-name followed by the template-arguments of the class template specialization or partial specialization enclosed in <>. [ Example:

template<template<class> class T> class A { };
template<class T> class Y;
template<> class Y<int> {
    Y* p;                                // meaning Y<int>
    Y<char>* q;                          // meaning Y<char>
    A<Y>* a;                             // meaning A<::Y>
    class B {
        template<class> friend class Y;  // meaning ::Y
    };
};

—end example ]

这基本上是为了方便起见,因此类中的类名指的是类本身,而不是任何可能具有相同名称的外部内容。对于类模板,如果模板参数列表很长,它可能会节省大量输入。

关于c++ - 在没有模板参数的类模板中使用类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30891207/

相关文章:

c++ - 使用指针对单链表进行排序

javascript - 渲染模板的部分内容

c++ - BOOST_STRONG_TYPEDEF 上的 numeric_limits 是错误的

c++ - 用蒙特卡洛方法估计 Pi,循环似乎提前终止

android - 用基于 ffmpeg 的编码器替换标准的 Android H264 软件编码器

c++ - 如果我在我的 C++ 项目中使用 C 样式转换,是否值得重构为 C++ 转换?

c++ - 如果我只有依赖程序的 .o 文件,我可以在可执行文件中反射(reflect)头文件的变化吗

c++ - 链接错误 : templated friend operator overload

c++ - 模板参数在部分特化中不可推导

c++ - 检查指向基类的指针是否是使用可变参数模板派生的指针之一