替代前瞻性声明 [英] Alternative to forward declaration
问题描述
我注意到,在 class
或 struct
关键字之前添加一个需要预先声明的类型,就像该类型已经转发一样声明:
I noticed that prepending the class
or struct
keyword to a type that would otherwise need be forward declared works as if that type was forward declared:
// struct Test; forward declaration commented
void* foo(struct Test* t) // C style function parameter - This works !
{
return t;
}
我没有意识到.我想知道它是标准的C ++还是扩展名,以及该参数前的 struct
关键字是否可用作前向声明或引入其他机制.
I wasn't aware of that. I wonder if it's standard C++ or an extension and whether the struct
keyword before the parameter works as a forward declaration or another mechanism kicks in.
此外,这种用法之后,"next"函数可以使用该类型而无需添加任何关键字:
Furthermore, after such a usage the "next" function can use the type without prepending any keywords :
void* oof(Test* t);
推荐答案
这是合法的,但可能不是一个好主意.
This is legal, but probably not a good idea.
来自 [basic.scope.pdecl] /6:
[...]-用于修饰形式说明符,形式为
class-key 标识符
如果在 decl-specifier-seq 或 parameter-declaration-clause 的 decl-specifier-seq 或 parameter-declaration-clause 中使用了在名称空间范围中定义的函数, 标识符在以下名称空间中声明为 class-name 包含声明 [...]
[...] — for an elaborated-type-specifier of the form
class-key identifier
if the elaborated-type-specifier is used in the decl-specifier-seq or parameter-declaration-clause of a function defined in namespace scope, the identifier is declared as a class-name in the namespace that contains the declaration [...]
例如:
namespace mine {
struct T* foo(struct S *);
// ^^^^^^^^^---------------- decl-specifier-seq
// ^^^^^^^^^^--- parameter-declaration-clause
}
这将 T
和 S
作为类名引入,并将 foo
作为函数名引入到 namespace mine
中.
This introduces T
and S
as class-names and foo
as a function name into namespace mine
.
请注意,C语言中的行为是不同的;struct名称仅在函数范围内有效.
Note that the behavior is different in C; the struct name is only valid within the scope of the function.
6.2.1标识符范围
4-[...]如果声明符或类型说明符声明标识符出现在...的参数声明列表中一个函数定义,该标识符具有 block作用域,其终止于关联的块.如果出现声明标识符的声明符或类型说明符在函数原型(不属于函数的一部分)的参数声明列表中定义),该标识符具有函数原型作用域,该作用域终止于函数声明符.
6.2.1 Scopes of identifiers
4 - [...] If the declarator or type specifier that declares the identifier appears [...] within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block. If the declarator or type specifier that declares the identifier appears within the list of parameter declarations in a function prototype (not part of a function definition), the identifier has function prototype scope, which terminates at the end of the function declarator.
gcc针对此用法在C代码中给出适当的警告:
gcc gives an appropriate warning for this usage in C code:
a.c:3:18: warning: ‘struct Test’ declared inside parameter list
void* foo(struct Test* t)
^
a.c:3:18: warning: its scope is only this definition or declaration, which is probably not what you want
这篇关于替代前瞻性声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!