c++ - 为什么 typedef 模板是非法的?

标签 c++ templates language-lawyer

从实际的角度来看,我理解 typedeftest 都有些“多余”,如果我们要编译以下代码,则需要将其删除:

template< typename type_t >
typedef struct tagTest
{
    int a;
} test;

但是,我认为 typedef 声明集是声明集的子集。他们只是碰巧有那个特定的 decl-specifier。这是我的合理化

typedef struct tagTest
{
    int a;
} test;

引入标识符test声明结构tagTest。如果该解释是正确的,那么标准中的以下段落应该允许 template typedef(尽管不是关键字 using 给出的含义) >).

The declaration in a template-declaration shall — (1.1) declare or define a function, a class, or a variable, or — (1.2) define a member function, a member class, a member enumeration, or a static data member of a class template or of a class nested within a class template, or — (1.3) define a member template of a class or class template, or — (1.4) be an alias-declaration.

我的推理看不出错误,但结论是非法的。

解决上述难题的标准有哪些相关部分?


更新 上述推理的一部分使用了 typedef struct 声明结构的事实。 typedef 说明符,据我所知,意味着声明的任何变量都是真正的类型。也就是说,typedeftest 从单纯的变量升级为等同于声明的 tagTest 的类型。这就是以下代码编译的原因(尽管有警告)。

typedef struct tagTest
{
    int a;
};
tagTest t;

其中一个答案负责多余的测试。但是,可以在没有声明符的情况下使用 typedef because “在声明命名类/结构/union 或命名枚举时,初始化声明器列表是可选的”

最佳答案

Template typedefs不允许在 C++11 之前和 C++11 中使用 template aliases被引入来解决这些问题。 CFR。 C++ template typedefswikipedia .

因为,正如您所指出的,标准不允许 typedef 在那里,代码是无效的

alias-declaration:

 using identifier attribute-specifier-seqopt= type-id ;

typedef 声明不是别名声明

此外,如果您要声明类模板,则不能有声明符,这是标准明确禁止的

[温度]/p3

In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the declaration shall contain at most one declarator. When such a declaration is used to declare a class template, no declarator is permitted.

所以即使是下面的也不会编译

template< typename type_t >
struct tagTest
{
    int a;
} test;

编辑:

没有明确说明

typedef struct S { };

应该是一个错误,因此 gcc 和 clang 都接受它并发出警告。我假设 Clang 依靠 [temp]/3 发出错误,以防 typedef 与模板一起使用,而 gcc 立即拒绝此代码

template<typename T>
typedef struct S { };

比较。 clang 错误22249

关于c++ - 为什么 typedef 模板是非法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30861592/

相关文章:

c++ - 测量 C++ 中的执行时间 : clock() and clock_gettime() give absolutely different results

c++ - Eigen3 replicate() 用于矩阵 vector cwiseProduct 操作

c++ - 在不违反 DRY 原则的情况下对传递的函数对象的参数类型进行模板选择

c++ - decltype(void()) 中的 void() 究竟是什么意思?

python - 如何使 DeepDiff 输出人类可读?

c++ - 可以在 constexpr 构造函数(C++14)中修改非静态成员变量吗?

css - 如何为 joomla 中的每个模板添加不同的 css 类

C++模板特化方法问题

c++ - std::add_const 和类似的用例

c++ - rethrow_exception 真的可以抛出相同的异常对象,而不是一个拷贝吗?