简体   繁体   English

在命名空间内定义一个 function 或限定?

[英]Define a function inside a namespace or qualified?

I see two styles in our codebase.我在我们的代码库中看到了两个 styles。 Simple question: what is to prefer?简单的问题:更喜欢什么?

void
someNsName::someFunc( int a, int b )
{/*...*/}

void
someNsName::someOtherFunc( int c )
{/*...*/}

or或者

namespace someNsName {
void
someFunc( int a, int b )
{/*...*/}

void
someOtherFunc( int c )
{/*...*/}
} // NS someNsName

I personally prefer the latter, especially when you would have to qualify a lot from someNsName otherwise.我个人更喜欢后者,尤其是当您必须从someNsName中获得很多资格时。 But are there more reasons?但是还有更多的原因吗?

The biggest difference between the two is that a function cannot be first declared by a qualified name.两者最大的区别是function不能用限定名声明。

// header
namespace foo {
    void bar(int);
}

// implementation
namespace foo {
    void bar(long) {
    } 
}

I made a mistake in the argument list.我在参数列表中犯了一个错误。 It declares an overload instead of the function I intended.它声明了一个重载,而不是我想要的 function。 The problem will only likely be caught during linking.问题只会在链接期间被发现。 Which isn't too bad, but could still take some time to actually popup.这还不错,但仍然需要一些时间才能真正弹出。 Had I written the implementation as如果我把实现写成

void foo::bar(long) {
}

It would have been an immediate compiler error when the implementation file is compiled.编译实现文件时会立即出现编译器错误。 There is no such function previously declared in foo , so I can't define it.之前在foo中声明的没有这样的 function ,所以我无法定义它。

For long namespace lists one could always do对于长名称空间列表,人们总是可以这样做

namespace impl = some::other::ns;

void impl::bar() {}

That's the most important difference between the two approaches, I think.我认为这是两种方法之间最重要的区别。 But again, both styles have (different) merits, so either one will do so long as we are consistent.但同样,styles 都有(不同的)优点,所以只要我们保持一致,任何一个都可以。

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

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