在没有模板参数的类模板中使用类名 [英] using class name in a class template without template parameters

查看:267
本文介绍了在没有模板参数的类模板中使用类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

the code comes from a C++ book as below:

为什么这个public成员Link *下没有typename参数?

Why does this public member Link* next have no typename argument?

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
    }
};

我想应该是链接< E> *下一页

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

Please tell me the reason it doesn't have a template argument.

推荐答案

这被称为注入的类名。规则特别来自[temp.local]:

This is known as the "injected class name." The rule specifically comes from [temp.local]:


类似于普通的(非模板)类,类模板有一个 -class-name (第9条)。 injected-class-
name
可用作模板名称类型名称。当与模板模板参数列表一起使用
作为模板模板参数模板参数作为朋友类模板声明的 elaborated-type-specifier
中的最终标识符,它指的是类模板本身。否则,它等同于
template-name 后面是<>

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

在类模板专业化或部分专门化的范围内,当 injected-
用作 type-name ,它等效于 template-name 后跟类$的模板参数 b $ b模板专用化或部分专业化,包含在<>中。 [示例:

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]

—end example ]

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

This is basically for convenience, so that the class name within the class refers to the class itself and not anything external which may have the same name. For class templates, it potentially saves a lot of typing if you have a long template argument list.

这篇关于在没有模板参数的类模板中使用类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆