在C ++ 11项目中,我想将标准库命名空间(std
)中的一些标识符引入项目的命名空间(proj
)以提高可读性。例如,我希望能够在任何地方使用string
而不是std::string
。
请注意,此项目是一个应用程序,而不是其代码随后将被其他项目包含的库。
这可以通过将代码添加到项目中包含的公共头中来实现。实际引入标识符的两种方法如下所示:
#ifndef PROJ_H
#define PROJ_H
#include "stuff.h"
#include <string>
namespace proj
{
// method 1 - using declaration
using std::string;
// method 2 - type alias
using string = std::string;
}
#endif
我觉得方法2优于方法1.原因是如果stuff.h
向匿名命名空间引入string
标识符,则在string
内使用proj
{1}}名称空间不明确。
我的问题:
std::make_unique
之类的函数)实现相同的安全级别。答案 0 :(得分:1)
两种方式都相同,您可以通过在命名空间中使用static_assert
来证明这一点。
static_assert(std::is_same<std::string, string>::value, "types are not the same"); // succeeds and does NOT complain
匿名命名空间的字符串标识符然后使用proj命名空间内的字符串将是不明确的。
在这种情况下,您只需编写::string
来指定要使用的字符串。
::string s1;
string s2;
您可以做的是在命名空间proj
中引入新类型或typedef-name。我更喜欢使用using declaration
表示它仍然是同一类型。尽管别名声明没有引入新类型,但它对于语义来说感觉就像是一个新类型 - 但这只是个人的事情。