c++ - 使用 "using"指令来缩短函数定义

标签 c++ namespaces

我偶然发现了 using namespace 指令的不寻常用法:

给定一个头文件WeirdNamespace.h:

namespace WeirdNamespace
{

class WeirdClass
{
public:
    int x;

    void go();
};

}

我有一个匹配的“WeirdNamespace.cpp”:

#include "WeirdNamespace.h"

#include <iostream>

using namespace WeirdNamespace;

void WeirdClass::go()
{
    std::cout << "Reached go?!" << std::endl;
}

该类的使用方式如下:

#include "WeirdNamespace.h"

int main(int argc, const char * argv[])
{   
    WeirdNamespace::WeirdClass c;
    c.go();
}

到目前为止,我从未见过使用 using 指令来避免重新打开 cpp 文件中的命名空间或在方法名称前添加命名空间名称的前缀。该指令的正确用法吗?除了通常的 using namespace 警告之外,此场景是否存在任何特定的陷阱?

最佳答案

你可能会这样做:

namespace WN = WeirdNamespace;
WN::WeirdClass c;

现在,我得到了问题!以上是没有答案

引用[7.3.4]使用指令

"During unqualified name lookup (3.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace."

因此,您在源代码中的定义无需将其包含在命名空间中即可。

关于c++ - 使用 "using"指令来缩短函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18556714/

相关文章:

c++ - 我可以重载插入运算符以采用模板化 STL 容器吗?

c++ - new char(size) 在 C++ 中是什么意思?

c++ - 将 long int 转换为 wxString

unity3d - 命名我的 Unity 项目脚本

php - 在 php 命名空间中,我是否需要要求每个文件

sql - 获取 dc :creator using SQL XML 的值

c++ - 堆栈模板不编译推送功能

linq - 缺少命名空间,LINQ 可以在 Web 应用程序中运行,但不能在网站中运行!

c# - 如何将非命名空间类型导入 IronPython?

c++ - 去初始化成语期间是否有任何动态绑定(bind)