代码之家  ›  专栏  ›  技术社区  ›  missingfaktor Kevin Wright

将“using”指令限制为当前文件

  •  5
  • missingfaktor Kevin Wright  · 技术社区  · 15 年前

    对不起这个愚蠢的问题,但有什么办法可以限制吗 using 对当前文件的指令,以便它们不会传播到 #include 这个文件?

    3 回复  |  直到 15 年前
        1
  •  4
  •   Nick Dandoulakis    15 年前

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

    // 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
    ...
    
        2
  •  15
  •   anon    15 年前

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

        3
  •  4
  •   visitor    15 年前

    从技术上讲,您应该能够将它们导入到一些内部名称空间,然后使在该名称空间中声明的内容在用户专用的名称空间中可见。

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

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

    推荐文章