强制一个包含文件包含在另一个之前 [英] Force one include file to be included before another

查看:194
本文介绍了强制一个包含文件包含在另一个之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有两个 .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(){
/ *做相同的东西,不使用some_function_1()* /
}
#endif
#endif

当我不知道文件是以什么顺序包含时,我的问题出现,例如:
main .cpp 我可以有像:

  #includefile1.hpp
#includefile2.hpp
int main(){
some_function_2();
/ *将调用使用some_function_1()的函数* /
}

  #includefile2.hpp
#includefile1.hpp
int main (){
some_function_2();
/ *将调用不使用some_function_1()的函数* /
}


$ b b

有一种方法可以确保一旦 file1.hpp file2.hpp
,则 some_function_2()将调用 some_function_1()



PS:一个解决方案是在 file2.hpp 中加入 file1.hpp 不能做
,因为我开发一个代码,可能或可能不依赖于最终用户可能有或可能没有的一些库



PPS:我可以想到的唯一的其他解决方案(即使我不知道如何
实现这一点)是删除的定义 some_method_2()包含
file1.hpp ,然后重新包含 file2.hpp p>

解决方案

我相信正确的解决方案是使用SFINAE机制重写 some_function_2()和模板而不是预处理技巧。这样,实例化将发生在cpp文件中,如果 some_function_1()存在,并且include的顺序不重要。


Imagine I have two .hpp files:

#ifndef _DEF_FILE_1_
#define _DEF_FILE_1_
inline void some_function_1(){
    /*do stuff*/
}
#endif

and

#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

My problem arises when I don't know in which order the files are included, e.g: in the main.cpp i can have something like :

#include "file1.hpp"
#include "file2.hpp"
int main(){
    some_function_2();
    /*will call the function that uses some_function_1()*/
}

or

#include "file2.hpp"
#include "file1.hpp"
int main(){
    some_function_2();
    /*will call the function that doesn't use some_function_1()*/
}

Is there a way to make sure that as soon as both file1.hpp and file2.hpp are included, then some_function_2() will call some_function_1()?

PS: One solution would be to include file1.hpp in file2.hpp but I can't do that because I developp a code that may or may not depend on some library that the end-user may or may not have.

PPS: The only other solution I can think of (even if I don't know how to achieve this) would be to "delete" the definition of some_method_2() when file1.hpp is included and then reinclude file2.hpp.

解决方案

I believe proper solution would be to rewrite some_function_2() using SFINAE mechanism and template instead of preprocessor tricks. That way instantiation will happen in cpp file where it would be known if some_function_1() exists and order of include will not matter.

这篇关于强制一个包含文件包含在另一个之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆