c++ - 强制将一个包含文件包含在另一个文件之前

标签 c++ conditional-compilation

假设我有两个 .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.hppfile2.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/

相关文章:

xcode - 忽略 Xcode 5 编译中的 ios8 代码

c# - 在 .Net 中是否可以仅从客户端程序集的调试版本中调用某些代码?

c++ - 开发文件压缩应用程序

c++ - 如果存在可以匹配另一个重载函数的函数模板,将调用哪个函数?

c++ - undefined symbol __istype with/opt/local/bin/g++?

由 小码哥发布于 2019-12-09 17:00:01 c++ #ifdef Mac OS X 问题

c++ - 无法使方法存在检测机制起作用

c++ - Linux 中的并发系统调用

c++ - 在网上找类似的源码

c++ - "has_trivial_destructor"定义而不是 "is_trivially_destructible"