Restricting `using` directives to the current file

痴心易碎 提交于 2019-12-23 10:14:32

问题


Sorry for this silly question, but is there any way to restrict using directives to the current file so that they don't propagate to the files that #include this file?


回答1:


Perhaps wrapping the code to be included inside its own namespace could achieve the behavior
you want, since name spaces have scope affect.

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

and in some other file

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



回答2:


No, there isn't, which is why you should not use using directives in header files, or any other file that you #include.




回答3:


Technically you should be able to import them to some internal namespace, and then make the things declared in that visible in the namespace meant for the user.

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

Not sure if it is worth the trouble and how well it plays with "argument-dependent lookup".



来源:https://stackoverflow.com/questions/2577557/restricting-using-directives-to-the-current-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!