假设我有两个 .hpp
文件:
#ifndef _DEF_FILE_1_
#define _DEF_FILE_1_
inline void some_function_1(){
/*do stuff*/
}
#endif
和
#ifndef _DEF_FILE_2_
#define _DEF_FILE_2_
#ifdef _DEF_FILE_1_
inline void some_function_2(){
/*do stuff using some_function_1()*/
}
#else
inline void some_function_2(){
/*do the same stuff without using some_function_1()*/
}
#endif
#endif
当我不知道文件的包含顺序时,我的问题就出现了,例如:
在 main.cpp
我可以有类似的东西:
#include "file1.hpp"
#include "file2.hpp"
int main(){
some_function_2();
/*will call the function that uses some_function_1()*/
}
或
#include "file2.hpp"
#include "file1.hpp"
int main(){
some_function_2();
/*will call the function that doesn't use some_function_1()*/
}
有没有办法确保 file1.hpp
和 file2.hpp
包含在内,那么 some_function_2()
将调用 some_function_1()
?
PS:一种解决方案是将 file1.hpp
包含在 file2.hpp
中,但我做不到
那是因为我开发了一个可能依赖也可能不依赖某些库的代码
最终用户可能有也可能没有。
PPS:我能想到的唯一其他解决方案(即使我不知道如何
实现这个)将是“删除” some_method_2()
的定义
包含 file1.hpp
,然后重新包含 file2.hpp
。
最佳答案
我认为正确的解决方案是使用 SFINAE 机制和模板而不是预处理器技巧重写 some_function_2()
。这样实例化将在 cpp 文件中发生,如果 some_function_1()
存在并且包含的顺序无关紧要,就会知道。
关于c++ - 强制将一个包含文件包含在另一个文件之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32631513/