类模板实例化报错:基类未定义的原因分析
编译错误原因分析:InheritableAccess模板实例化失败
原模板代码
template <typename T, typename VT, typename PF, typename ... Sub> class InheritableAccess; template <typename T, typename VT, typename PF, typename F, typename ... Sub> class InheritableAccess<T, VT, PF, F, Sub...> : public InheritableAccess<T, typename F::Type, F, Sub...>{}; template <typename T, typename PF, typename ... Sub> class InheritableAccess<T, T, PF, Sub...>{};
尝试的实例化代码
internal::InheritableAccess<inheritable, sub1::Type, sub1, sub2> t;
编译错误信息
Test.h(32,1): error C2504: 'internal::InheritableAccess<T,SubItem2,F>': base class undefined 1> with 1> [ 1> T=inheritable, 1> F=sub2 1> ] 1>test-project2.cpp(21): message : see reference to class template instantiation 'internal::InheritableAccess<inheritable,SubItem1,sub1,sub2>' being compiled
错误原因解析
我们一步步拆解模板实例化的递归过程:
- 实例化
InheritableAccess<inheritable, sub1::Type, sub1, sub2>时,匹配到第二个偏特化(带F和Sub...的版本)。 - 该偏特化的基类会被实例化为
InheritableAccess<inheritable, typename sub2::Type, sub2>。 - 现在看这个基类的模板参数:共3个,分别是
inheritable、sub2::Type、sub2。此时:- 它不匹配第三个偏特化:第三个偏特化要求第二个模板参数必须等于第一个(即
VT=T),但这里sub2::Type不等于inheritable。 - 它也不匹配第二个偏特化:第二个偏特化要求至少4个模板参数(因为模板参数列表包含
F和可变参数Sub...,对应实例化至少需要4个参数),但这里只有3个。 - 主模板仅做了声明,没有提供类定义,编译器无法找到该基类的实现,因此抛出
base class undefined错误。
- 它不匹配第三个偏特化:第三个偏特化要求第二个模板参数必须等于第一个(即
内容的提问来源于stack exchange,提问作者Niclas Lindgren
相关产品推荐
相关产品推荐

