C ++使用std和boost命名空间的最佳实践 [英] C++ using for std and boost namespace best practice

查看:260
本文介绍了C ++使用std和boost命名空间的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Possible Duplicate:
Do you prefer explicit namespaces or 'using' in C++?














$ b b
$ b

我的一个C#开发人员,但我的朋友是一个C + +,他已经显示我的代码,充满了调用像std :: for_each和boost :: bind,im用于在C#中使用,并认为使用指令会让代码的可读性和通常更快的开发摇摆,在C#foreach语句之前键入任何命名空间将是一个痛苦。

Hi guys Im a C# developer, but my friend is a C++ one and he has shown me the code which is filled with calls like std::for_each and boost::bind , im used to using in C# and thought that using directives would rock for readability of code and generally faster development , it would be a pain in the neck to type any namespace before C# foreach statement for example.

使用这种流行的命名空间,我想知道什么缺点和优点?
是否最好包含这些命名空间?

What are the cons and pros of using for such popular namespaces I am wondering? Is it a best practice to include those namespaces or not?

推荐答案

首先,让我们做两个区别:

First of all, let's make two distinctions:

1)使用使用命名空间std; ,并使用 using std :: cout;

2)可以在头文件(.h)或实现文件中使用指令和声明。 cpp)

2) You can put using directives and declarations in either a header (.h) or an implementation file (.cpp)

此外,使用指令和声明将名字带入它们所写的命名空间,即

Furthermore, using directives and declarations bring names into the namespace in which they're written, i.e.

namespace blah
{
    using namespace std; // doesn't pollute the *global* namespace, only blah
}

在最佳实践方面,很明显,在全局命名空间中的头文件中使用指令和声明是一个可怕的no-no。人们会憎恨你,因为任何包含该头的文件都会被其全局命名空间污染。

Now, in terms of best practice, it's clear that putting using directives and declarations in a header file in the global namespace is a horrible no-no. People will hate you for it, because any file that includes that header will have its global namespace polluted.

在实现文件中使用伪指令和声明是可以接受的,虽然它可能或不会使代码不太清楚。通常,您应该更喜欢在这种情况下使用声明来使用指令。我自己的偏好是总是指定命名空间,除非它是恼人的长(那么我可能会被诱惑)。

Putting using directives and declarations in implementation files is somewhat more acceptable, although it may or may not make the code less clear. In general, you should prefer using declarations to using directives in such instances. My own preference is to always specify the namespace, unless it's annoyingly long (then I might be tempted).

在标题中,如果每次键入命名空间真的很繁琐,你总是可以引入一个本地命名空间,例如

In a header, if typing the namespace every single time is getting really tedious, you can always introduce a "local" namespace, e.g.

namespace MyLocalName
{
    using namespace boost;

    class X
    {
        // can use things from boost:: here without qualification
    };
}

using MyLocalName::X; // brings X back into the global namespace

但不要使用命名空间boost ; 或等效的地方,它会将所有的东西从Boost拖动到其他人的全局命名空间本身。

But never put using namespace boost; or the equivalent somewhere where it will drag all the stuff from Boost into the global namespace itself for other people.

这篇关于C ++使用std和boost命名空间的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆