外部模板和类型不完整 [英] extern template & incomplete types
问题描述
最近,当我尝试优化自己的包含层次结构时,偶然发现文件 a.hpp
:
Recently when I was trying to optimize my include hierarchy I stumbled upon the file a.hpp
:
template<class T>
class A
{
using t = typename T::a_t;
};
class B;
extern template class A<B>;
这似乎是错误的形式.实际上,似乎最后一个extern模板语句会导致 A< B>
的实例化,这会导致编译器抱怨类型不完整.
which seems to be ill-formed. In fact it seems as if the extern template statement at the end causes an instantiation of A<B>
which causes the compiler to complain about an incomplete type.
我的目标是在 a.cpp
中定义 A< B>
:
#include <b.hpp>
template class A<B>;
这样,我避免了必须包含 a.hpp
中的 b.hpp
,这似乎是减少编译时间的好主意.但是,它不起作用( a.hpp
本身无法编译!)还有更好的方法吗?
This way I avoid having to include b.hpp
from a.hpp
which seems like a good idea to reduce compile time. However it does not work (a.hpp
on itself doesn't compile!) Is there a better way of doing this?
注意:当然,我不能只使用显式模板实例化,但这不是我想要的!如果要使用 A< B>
,我想对其进行预编译"以节省编译时间,但是如果不使用 A< B>
,则我不想包括在内每个使用 a.hpp
的文件中的 b.hpp
!
Note: Of course I could just not use explicit template instantiation but this is not what I want! I would like to "precompile" A<B>
to save compilation time if it were used, but if A<B>
is not used I don't want to include b.hpp
in every file that uses a.hpp
!