更智能地在C++中包含保护,以便在不同的命名空间中多次包含标头
Smarter include guard in C++ to include headers several times inside different namespaces
我需要一种方法来更好地#include
C++守卫。
当包含两次相同的标头时,应忽略第二个#include
(这很简单(:
#include "header1.hpp"
#include "header2.hpp"
#include "header1.hpp" //Should be ignored
但是,当嵌套命名空间中包含相同的标头时,应再次包含它(但每个命名空间不超过一次(:
#include "header1.hpp"
#include "header2.hpp"
namespace foo_namespace {
//May be this one is needed?
#define NAMESPACE_ID foo_namespace
#include "header1.hpp" //Should be included again
#include "header1.hpp" //Should be ignored
#undef NAMESPACE_ID
};
问题是:我应该如何保护header1.hpp
内部的代码? 额外的要求是保护本身应该是可重用的(定义为宏(,因为我有很多标题应该以这种方式保护。
一个不错的解决方案是拥有一个没有防护装置的标头版本:
// header_noguard.hpp
// the declarations ...
// header.hpp
#pragma once // or a macro of your choice
#include "header_noguard.hpp"
// header_namespace.hpp
#pragma once // or a macro of your choice
namespace foo_namespace {
#include "header_noguard.hpp"
};
现在,您可以多次包含header.hpp
和header_namespace.hpp
。每个都防止多个包含,但都包含各自命名空间中的声明。
相关文章:
- 使用 Clang++ 有没有办法将文件作为命名空间等包含?
- 命名空间 std:: 不包含可选
- 更智能地在C++中包含保护,以便在不同的命名空间中多次包含标头
- 在命名空间内使用函数的循环包含
- Catalina C++:使用<cmath>标头产生错误:全局命名空间中没有名为 'signbit' 的成员
- 如何在两个不同的命名空间(但只写一次)中使用相同的标头定义,命名空间有不同的实现?
- 我可以停止 GCC 将标准库名称包含在全局命名空间中吗?
- 即使在包含 std 命名空间之后,fstream 在 Visual Studio 2017 中也无法正常工作
- 在命名空间中包含旧库C++
- 我可以在标头中将一个命名空间"import"到另一个命名空间中吗?
- 如何修复带有命名空间的标头中常量的重定义错误?
- 包含所有命名空间 std 的文件
- 为什么我不能在标头中只定义一个非常量 gloabal 变量?如果我使用命名空间,为什么我必须声明它"extern"?
- 命名空间、标头和对象的层次结构
- 在 C++ 命名空间中包含 C 标头 - 这是标准行为吗?
- 如何在vc++中将命名空间包含在另一个项目的另一个文件中
- 使用 clang 解析命名空间:在另一个源文件中包含标头或直接解析标头时,AST 差异
- 在自定义命名空间下包含一个标头
- Xcode 标头错误 - 命名空间'_STL'未包含命名空间'_Rep'
- visual C/C++命名空间在标头问题中