我需要一种方法来做得更好 #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.hpp
和 header_namespace.hpp
多次。每个都受到保护,防止多次包含,但都在各自的命名空间中包含声明。
关于c++ - 在 C++ 中更智能的包含保护以在不同的命名空间中多次包含头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59265588/