下面是两个案例。
情况 1) Base->BaseIndirect->DerivedIndirect
情况 2) 基础->派生
在案例 2) 中,我可以使用 3 个符号调用基类的模板函数。
在情况 1) 中,我可以仅使用其中一种符号来调用基类的模板函数。而且,我无法使用任何符号调用 BaseIndirect 的模板函数:(。我该如何解决这个问题?谢谢。
struct Base {
template<bool R> inline void fbase(int k) {};
};
template<class ZZ> struct BaseIndirect : Base {
template<bool R> inline void fbaseIndirect(int k) {};
};
template<class ZZ>
struct DerivedIndirect : BaseIndirect<ZZ> {
DerivedIndirect() {
this->fbase<true>(5); // gives error, line 13
fbase<true>(5); // gives error, line 14
Base::fbase<true>(5); // WORKS, line 15
this->fbaseIndirect<true>(5); // gives error, line 16
fbaseIndirect<true>(5); // gives error, line 17
BaseIndirect<ZZ>::fbaseIndirect<true>(5); // gives error, line 18
}
};
template<class ZZ>
struct Derived : Base {
Derived() {
this->fbase<true>(5); // WORKS
fbase<true>(5); // WORKS
Base::fbase<true>(5); // WORKS
}
};
int main() {
Derived<int> der;
DerivedIndirect<int> derIndirect;
};
编译时出错
test.cpp: In constructor 'DerivedIndirect<ZZ>::DerivedIndirect()':
test.cpp:14: error: 'fbase' was not declared in this scope
test.cpp:17: error: 'fbaseIndirect' was not declared in this scope
test.cpp: In constructor 'DerivedIndirect<ZZ>::DerivedIndirect() [with ZZ = int]':
test.cpp:34: instantiated from herep
test.cpp:13: error: invalid operands of types '<unresolved overloaded function type>' and 'bool' to binary 'operator<'
test.cpp:16: error: invalid operands of types '<unresolved overloaded function type>' and 'bool' to binary 'operator<'
test.cpp:18: error: invalid operands of types '<unresolved overloaded function type>' and 'bool' to binary 'operator<'
许多这些调用失败的原因是存在语法歧义,您需要使用最晦涩的用法来解决template
关键词。而不是写作
this->fbase<true>(5);
你需要写
this->template fbase<true>(5);
原因是如果没有template
关键字,编译器将其解析为
(((this->fbase) < true) > 5)
这是荒谬的。 template 关键字明确消除了这种歧义。添加template
关键字进入您提到的其他情况应该可以解决这些问题。
我实际上不确定为什么这适用于直接基类,所以如果有人可以回答问题的这一部分,我很想看看答案是什么。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)