函数定义先于命名空间中的声明

Function definition precedes declaration in namespace

以下代码(其中函数定义先于其声明)在 VS .NET 2008 和 Cygwin gcc 4.8.2 中编译。合法吗?

namespace N
{
    int init()      // Definition appears first
    {
        return 42;
    }       
}

namespace N
{
    int init();     // followed by declaration
    const int x = init();
}

int main()
{
}

编辑

我想这与下面的编译没有太大区别

void foo()
{
}

void foo();

int main()
{
}

[basic.def]/1:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.

可以随时(重新)声明名称,只要声明与之前的名称一致即可。在这种情况下,它是一致的,因为两个声明中 init 的类型都是 int()。所以是的,代码格式正确。

3.3.1/4 似乎涵盖了这一点:

Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,

— they shall all refer to the same entity, or all refer to functions and function templates; or

然后是 8.3.5/5:

A single name can be used for several different functions in a single scope; this is function overloading (Clause 13). All declarations for a function shall agree exactly in both the return type and the parameter type- list.

这似乎清楚地表明您可以通过声明 ...agree exactly in both the return type and the parameter type- list.

来声明同一个函数两次