C++ 修复基于模块的库中包含的自阻塞
我已经编写了一个简单的模板化、基于模块的头库。对于基于模块的,我的意思是一个只能包含C++ 修复基于模块的库中包含的自阻塞,c++,c++11,module,header,include,C++,C++11,Module,Header,Include,我已经编写了一个简单的模板化、基于模块的头库。对于基于模块的,我的意思是一个只能包含string.h或dynarray.h,并且头部将拉入其所有依赖项 现在,由于这个系统的工作方式,我面临着缺少类型的问题。 模块包括: #包括所有依赖项 定义接口类Foo #包括实施文件 不幸的是,在某些情况下,在包含任何实现之前,需要有两个接口可用。我在这里详细分析了这个问题: 字符串.h #pragma once // A string depends on a DynArray. #include "
string.h
或dynarray.h
,并且头部将拉入其所有依赖项
现在,由于这个系统的工作方式,我面临着缺少类型的问题。
模块包括:
所有依赖项#包括
- 定义接口
类Foo
实施文件#包括
#pragma once
// A string depends on a DynArray.
#include "dynarray.h"
template<typename E>
class String {
public:
DynArray<E> arr;
/* ... */
};
// Include the implementation of all the different functions (irrelevant here)
#include "string_impl.h"
由于在其底部包含模块的实现,当在某处包含string.h
时,dynarray\u impl.h
的内容及其out\u of_range\u exception.h
位于字符串类接口之前。因此,OutOfRangeException
中未定义String
显然,解决方案是在定义字符串接口之后只延迟dynarray(
dynarr_impl.h
)的实现部分。问题是,我不知道如何在不创建某种公共头文件的情况下执行此操作,这与基于模块的方法不兼容。您的问题是接口和实现都有一个文件
#包括
根据X的接口和X的实现,选择该文件表示的内容
有时,您只想依赖于X的接口
X接口:
#包括接口的所有依赖项
- 定义接口
类X
接口#包括
#包括实现的所有依赖项
- 定义
类X的实现
#包括“X.h”
,除非您对实现有循环依赖关系。然后在某个地方你必须用一个#include“X_interface.h”
如果您真的想使用单个头文件,您可以一次性删除
#pragma
,并将头文件包含在“两种模式”中。这会大大降低构建时间,因为任何这样的机制都需要编译器打开文件来检查那里是否有代码;大多数编译器可以检测#ifdef
头保护和#pragma一次
,避免重新打开它知道不包含任何感兴趣的文件。但是一个奇特的“可以在不同模式下多次包含”头文件不能用这种技术处理
#pragma once
// The dynarray header has no direct dependencies
template<typename E>
class DynArray {
public:
/* ... */
E& Get(int index);
};
// Include the implementation of all the different functions
#include "dynarray_impl.h"
#pragma once
// The dynarray implementation needs the OutOfRangeException class
#include "out_of_range_exception.h"
template<typename E>
E& DynArray<E>::Get(int index) {
if (index >= size) {
throw OutOfRangeException("Some error message");
}
}
class OutOfRangeException {
public:
String message;
OutOfRangeException(String message) {
/* ... */
}
};