简体   繁体   English

命名空间函数可以在块 scope 处声明吗?

[英]Can namespace functions be declared at block scope?

Can namespace functions be declared at block scope outside the namespace they were defined at?命名空间函数是否可以在其定义的命名空间之外的块 scope 处声明?

This code does not compile when DECLARED_IN_NS is defined as 1 :DECLARED_IN_NS定义为1时,此代码无法编译:

#define DECLARED_IN_NS 1 // can be either 0 or 1


#if DECLARED_IN_NS == 1
namespace ns
{
#endif

void
func1()
{
}

void
func2()
{
}

#if DECLARED_IN_NS == 1
} // namepace ns
#endif

int main( )
{
#if DECLARED_IN_NS == 1

    void ns::func1(); // compile error
    void ns::func2(); // compile error

    ns::func1();
    ns::func2();

#elif DECLARED_IN_NS == 0

    void func1();
    void func2();

    func1();
    func2();

#endif
}

It shows some errors:它显示了一些错误:

error: qualified-id in declaration before '(' token
   28 |     void ns::func1();
      |                   ^

The code compiles when func1 and func2 are defined at global namespace.func1func2在全局命名空间中定义时,代码会编译。 However, it doesn't compile when they are defined inside a namespace (eg ns ).但是,当它们在命名空间(例如ns )中定义时,它不会编译。

Is there a way to fix this?有没有办法来解决这个问题?

I can't find a definitive reference to this in the standard, but I don't think there'd be much point to allow it intentionally.我在标准中找不到对此的明确参考,但我认为故意允许它没有多大意义。

Even if it could appear at block scope, it'd be pointless.即使它能出现在 scope 区块,也没有意义。 A declaration that uses a nested name specifier cannot be the first declaration for an entity.使用嵌套名称说明符的声明不能是实体的第一个声明。

[dcl.meaning.general] [dcl.meaning.general]

1 When the declarator-id is qualified, the declaration shall refer to a previously declared member of the class or namespace to which the qualifier refers (or, in the case of a namespace, of an element of the inline namespace set of that namespace ([namespace.def]))... 1当 declarator-id 被限定时,声明应引用先前声明的 class 成员或限定符引用的命名空间(或者,在命名空间的情况下,该命名空间的内联命名空间集的元素( [命名空间.def]))...

This makes this code like this valid这使得这段代码有效

namespace ns
{
void func();

} // namepace ns


void ns::func(); // repeated declaration - optional
void ns::func() { // definition
}

Now, returning to the block scope case, you'd need a namespace scoped declaration preceding it anyway, so the whole exercise is moot.现在,回到块 scope 的情况,无论如何你都需要在它之前有一个命名空间范围的声明,所以整个练习没有实际意义。

Furthermore, the behavior of declaring functions in block scope has aspects that are aptly named by the c++ community , but it remains due to C compatibility.此外,在块 scope 中声明函数的行为具有由 c++ 社区恰当命名的方面,但由于 C 兼容性,它仍然存在。 It would certainly not be beneficial to allow it for nested names intentionally.故意允许它用于嵌套名称肯定不会有好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM