更智能地在C++中包含保护,以便在不同的命名空间中多次包含标头

Smarter include guard in C++ to include headers several times inside different namespaces

本文关键字:命名空间 包含标 C++ 智能 包含 保护      更新时间:2023-10-16

我需要一种方法来更好地#includeC++守卫。

当包含两次相同的标头时,应忽略第二个#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.hppheader_namespace.hpp。每个都防止多个包含,但都包含各自命名空间中的声明。