gpt4 book ai didi

c++ - gcc 编译器不显示类模板注入(inject)名称的正确错误

转载 作者:太空狗 更新时间:2023-10-29 21:24:25 24 4
gpt4 key购买 nike

最近在看书:C++ templates: the complete guide由 David Vandevoorde 和 Nicolai M. Josuttis 撰写。

特别是第 126 页中关于模板解析的引用。

Class templates also have injected class names, However, they are stranger than ordinary injected class names: They can be followed by template arguments (in which case they are injected class template names ), but if they are not followed by template arguments they represent the class with its parameters as its arguments (or, for a partial specialization, its specialization arguments).

书中除相关代码如下:

template<template<typename> class TT> 
class X
{
};

template <typename T>
class C
{
C* a; //OK, same as "C<T>* a"
C<void> b; // OK
X<C> c; //Error, C without a template argument list does not denote a template
X< ::C>d;
};

int main()
{
return 0;
}

上面的代码示例试图解释整个引用的段落。

我在 gcc 4.5.3 中编译了上面的代码,它输出:

error: field ‘b’ has incomplete type

因此,我有以下问题:

  1. 为什么编译器生成完全不同的错误消息?书上说b可以,但是 gcc 给出了错误;同时,书中列出的其他错误没有被检测到?为什么,这可能是编译器错误或书中的错误吗?
  2. 什么是injected class names意思?我如何识别哪些名称是 injected class names什么不是?
  3. 为什么 C*aC<T>* a相同?我试图替换 C*aC<T>* a ,没有报错,C* a也是C<T>* a 的简写?

非常感谢!

最佳答案

注意:injected-class-name 只是用于声明类的标识符(与其他也引用同一类的名称相反,例如 typedef 名称)。

这是 C++11 标准第 14.6.1p1 节的相关引述:

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++11 中是合法的。

然而,这本书正确地描述了 C++03 的行为:

Like normal (non-template) classes, class templates have an injected-class-name (clause 9). The injected-class-name can be used with or without a template-argument-list. When it is used without a template-argument-list, it is equivalent to the injected-class-name followed by the template-parameters of the class template enclosed in <>. When it is used with a template-argument-list, it refers to the specified class template specialization, which could be the current specialization or another specialization.

除了反转逻辑之外,我们还看到 C++03 包含一种情况,其中标识符引用模板(当提供模板参数时),C++11 添加了另外两种情况,其中一种会影响此代码。

所以在 C++03 中,代码相当于 X<C<T>> c; ,这是一个错误,因为 X需要传递模板而不是类型。

底线:要学习语言,尤其是模板,您需要 a book on C++11 .较旧的书籍在架构和高级设计方面仍然有用,但无法解释出版后发生变化的语言复杂性。

关于c++ - gcc 编译器不显示类模板注入(inject)名称的正确错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16127770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com