c++ - 在 C++ 中更智能的包含保护以在不同的命名空间中多次包含头文件

标签 c++ macros namespaces include preprocessor

我需要一种方法来做得更好 #include在 C++ 中保护。

当相同的头被包含两次时,第二个 #include应该被忽略(这很简单):

#include "header1.hpp"
#include "header2.hpp"
#include "header1.hpp" //Should be ignored

但是当嵌套命名空间中包含相同的 header 时,则应该再次包含它(但每个命名空间不超过一次):
#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.hppheader_namespace.hpp多次。每个都受到保护,防止多次包含,但都在各自的命名空间中包含声明。

关于c++ - 在 C++ 中更智能的包含保护以在不同的命名空间中多次包含头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59265588/

相关文章:

c++ - OpenGL 临时缓冲区

macos - MacOS X 中未定义宏 `__unix__`

c - 通过带有变量名称的宏进行调试打印

php - 命名空间声明中的别名命名空间,而不是 PHP 中的命名空间导入可能吗?

c# - 从 IntelliSense 隐藏命名空间或更改建议命名空间的顺序(自定义 IntelliSense)

c++ - 链接器未在目标文件中找到现有引用

c++ - 如何在使用 gdb 调试期间从 stdin 读取?

c++ - 在返回值上调用 std::move - 签名应该是什么

java - 用于插入自定义代码 Eclipse 的键绑定(bind)键

c++ - C++ 命名空间中的内联函数