【问题标题】:concise syntax for c++ namespacec++命名空间的简洁语法
【发布时间】:2020-02-12 16:01:18
【问题描述】:

我想知道是否可以用更简洁的方式编写以下冗长的命名空间用法:

#include <iostream>
#include <iomanip>

using std::ostream;
using std::cout;
using std::endl;
using std::ios;
using std::setw;
using std::setfill;
using std::hex;

说:

using std::{ostream,cout,endl,ios,setw,setfill,hex}; // hypothetically, of course

【问题讨论】:

标签: c++ syntax namespaces std using


【解决方案1】:

你可以写

using std::ostream, std::cout, std::endl, std::ios, std::setw, std::setfill, std::hex;

前提是您的编译器支持标准 C++ 17。

然后我建议使用限定名称而不是使用声明引入的非限定名称。不合格的名称可能会使代码的读者感到困惑并造成歧义。

例如,如果代码的读者遇到名称hex,他会混淆它是标准操纵器std::hex 还是用户定义的名称。

通常使用声明用于在给定范围内引入重载函数或使基类成员的名称可见。

【讨论】:

  • 我希望没有人会被来自std 的不合格名称所迷惑。
  • @user253751 你错了。例如,如果您遇到名称 hex,则不清楚它是 std::hex 还是用户定义的名称。
  • 这似乎对 C++17 有效,但对早期版本无效 - en.cppreference.com/w/cpp/language/using_declaration
  • 确实这在 C++17 中似乎是新的。直到。请将该资格添加到答案中
  • 请注意,即使使用/std:c++latest,Microsoft 似乎仍然不支持这种语法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
  • 2011-07-31
  • 1970-01-01
  • 2013-02-03
相关资源
最近更新 更多