[英]c++ template trait — compiling without including header
How is it that this works? 这如何运作? Might be doing something wrong here.
可能在这里做错了。
def.H 清晰度
enum some_enum { FAKE = 0, };
template < some_enum T> struct example_trait;
trait_implementation.H 特质实施
#include "def.H"
template<> struct example_trait<FAKE> {
static constexpr size_t member_var = 3; };
generic_alg.H generic_alg.H
#include "def.H"
template < some_enum T, typename TT = example_trait<T> > void
function() { std::cout << TT::member_var << std::endl; }
main.C 主C
I can run this in my main as long as I include the headers in this order 只要按此顺序包含标题,我就可以在主目录中运行它
#include trait_implementation.H
#include generic_alg.H
int main() {
function<FAKE>();
return 0;
}
How is it that this compiles? 它如何编译? can generic_alg.H compiles with only a forward declared traits class.
可以使用常规声明的traits类编译generic_alg.H。 It can see the traits definition when included in the right order, even though generic_alg.H itself does not include the trait_implementation.H.
即使generic_alg.H本身不包含trait_implementation.H,也可以按正确的顺序查看traits定义。 How is that plausible?
这怎么可能呢?
Using an online compiler I can only re-create: https://onlinegdb.com/B1BEUlp7E 使用在线编译器,我只能重新创建: https : //onlinegdb.com/B1BEUlp7E
#include
is, for most practical purposes, a request to dump the contents of the include
-ed file directly into your source code. 在大多数实际情况下,
#include
是一个将include
-ed文件的内容直接转储到您的源代码中的请求。
So even though generic_alg.H
uses stuff it doesn't define or include, the only thing getting directly compiled is main.C
, and the complete definition from trait_implementation.H
is dumped into main.C
directly before generic_alg.H
, so the definition exists when it gets around to compiling the code from generic_alg.H
. 因此,即使
generic_alg.H
使用了未定义或包含的内容,唯一可以直接编译的是main.C
,而来自trait_implementation.H
的完整定义直接在generic_alg.H
之前转储到main.C
,因此定义存在于从generic_alg.H
编译代码的过程中。
Even though it works, it's still a bad idea, because now every source file that uses generic_alg.H
must explicitly include trait_implementation.H
first, and there is no obvious documentation making that dependency clear. 即使它起作用,也仍然不是一个好主意,因为现在每个使用
generic_alg.H
源文件都必须首先显式包含trait_implementation.H
,并且没有明显的文档可以清楚地表明该依赖性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.