【问题标题】:Restricting `using` directives to the current file将 `using` 指令限制为当前文件
【发布时间】:2011-02-04 08:59:09
【问题描述】:

抱歉这个愚蠢的问题,但有没有办法将using 指令限制到当前文件,以便它们不会传播到#include 这个文件的文件?

【问题讨论】:

  • 您可以将 using 指令限制在非文件范围内,例如命名空间或函数。
  • 最好不要在标题中应用using 指令。
  • @David:当我可以输入map<string, tuple<int, string> > 时,我讨厌输入std::map<std::string, std::tr1::tuple<int, std::string> > 之类的内容。

标签: c++ using-directives


【解决方案1】:

不,没有,这就是为什么您不应该在头文件或您#include 的任何其他文件中使用 using 指令。

【讨论】:

  • 稍微扩展一点——预处理器(处理#include 和其他#-命令)在编译器看到代码之前运行。 using 指令和任何其他标准关键字由编译器处理。因此,就编译器而言,头文件实际上并不是单独的文件 - 它们是恰好位于它们所在的每个文件中的代码 #include'd,因此任何 using 指令也是如此你可以把它们放进去。
  • 啊……伤心。无论如何感谢您的回答。
  • @Rahul 这还不错 - 您当然可以(并且应该)在 .cpp 文件中使用 using 指令。
【解决方案2】:

也许将要包含在自己命名空间中的代码包装起来可以实现该行为
你想要的,因为名称空间会影响范围。

// FILENAME is the file to be included
namespace FILENAME_NS {
   using namespace std;
   namespace INNER_NS {
      [wrapped code]
   }
}
using namespace FILENAME_NS::INNER_NS;

在其他文件中

#include <FILENAME>
// std namespace is not visible, only INNER_NS definitions and declarations
...

【讨论】:

  • 嘿,很酷的把戏!我想我会选择这个;非常感谢! :)
【解决方案3】:

从技术上讲,您应该能够将它们导入到某个内部命名空间,然后让其中声明的内容在对用户有意义的命名空间中可见。

#ifndef HEADER_HPP
#define HEADER_HPP

#include <string>

namespace my_detail
{
    using std::string;
    inline string concatenate(const string& a, const string& b) { return a + b; }   
}

namespace my_namespace
{
    using my_detail::concatenate;
}

#endif

#include <iostream>
#include "header.hpp"

using namespace my_namespace;

int main() 
{
    std::  //required
    string a("Hello "), b("world!");
    std::cout << concatenate(a, b) << '\n';
}

不确定是否值得麻烦,以及它在“依赖于参数的查找”方面的表现如何。

【讨论】:

  • 确实太麻烦了。但仍然是一个不错的工作。所以,+1。 :)
猜你喜欢
  • 2016-08-05
  • 2021-09-24
  • 1970-01-01
  • 2010-10-13
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多