c++ - using-declaration 不能命名命名空间

标签 c++ namespaces c++17 using

如果我有这样的文件,一切都会按预期工作:

#include <filesystem>
#include <iostream>
int main() {
   std::filesystem::path o = "C:\\Windows\\write.exe";
   auto s = o.parent_path();
   std::cout << s << std::endl;
}

不过,如果可能的话,我想使用这样的一行:

filesystem::path o = "C:\\Windows\\write.exe";

我试过了,但出现错误:

// using-declaration may not name namespace 'std::filesystem'
using std::filesystem;

还有这个错误:

using namespace std::filesystem;
// error: 'filesystem' has not been declared
filesystem::path o = "C:\\Windows\\write.exe";

是否有可能做我正在尝试的事情?

最佳答案

你可以使用像这样的命名空间别名

namespace filesystem = std::filesystem;

这是一个演示程序

#include <iostream>

namespace A
{
    namespace B
    {
        int x;
    }
}

int main() 
{
    namespace B = A::B;
    
    B::x = 10;
    
    std::cout << B::x << '\n';
    
    return 0;
}

它的输出是

10

关于c++ - using-declaration 不能命名命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63751519/

相关文章:

适用于 Google 财经的 C++ API

c++ - 无法在屏幕上我想要的位置绘制我的矩形

javascript - 为什么cb异步运行时仍然定义了这个var?

php - 为什么null可以写成反斜杠?

xml - 使用 xslt 将元素复制到新的命名空间

c++ - 状态模式 C++

C++ 不使用正则表达式的多个字符串匹配

C++ 17 : How to call a different constructor using if constexpr?

c++ - 比较 observer_ptr< T > 和 T *

c++ - 函数模板实例的地址可以作为函数指针传递给某个函数吗?