5

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

4

3 回答 3

15

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

于 2010-04-05T08:46:31.580 回答
4

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

// 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
...
于 2010-04-05T10:34:46.530 回答
4

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

#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';
}

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

于 2010-04-05T10:35:29.630 回答