从实际的角度来看,我理解 typedef
和 test
都有些“多余”,如果我们要编译以下代码,则需要将其删除:
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
说明符,据我所知,意味着声明的任何变量都是真正的类型。也就是说,typedef
将 test
从单纯的变量升级为等同于声明的 tagTest
的类型。这就是以下代码编译的原因(尽管有警告)。
typedef struct tagTest
{
int a;
};
tagTest t;
其中一个答案负责多余的测试
。但是,可以在没有声明符的情况下使用 typedef because “在声明命名类/结构/union 或命名枚举时,初始化声明器列表是可选的”
最佳答案
Template typedefs不允许在 C++11 之前和 C++11 中使用 template aliases被引入来解决这些问题。 CFR。 C++ template typedefs和 wikipedia .
因为,正如您所指出的,标准不允许 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/