首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++调用基类的模板函数

C++调用基类的模板函数
EN

Stack Overflow用户
提问于 2011-02-08 13:20:53
回答 1查看 8.1K关注 0票数 7

下面是两个案例。

情况1) Base->BaseIndirect->DerivedIndirect

情况2)基础->派生

在情况2)中,我可以使用3个符号调用Base类的模板函数。在情况1)中,我能够仅使用这些符号中的一个来调用基类的模板函数。而且,我不能使用任何符号调用BaseIndirect的模板函数:(.我该如何解决这个问题?谢谢。

代码语言:javascript
复制
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;
};                              

编译时出现的错误

代码语言:javascript
复制
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<'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-02-08 13:25:58

其中许多调用失败的原因是,您需要使用template关键字这一最晦涩的用法来解决语法上的歧义。而不是写作

代码语言:javascript
复制
this->fbase<true>(5);

你需要写下

代码语言:javascript
复制
this->template fbase<true>(5);

原因是如果没有template关键字,编译器会将其解析为

代码语言:javascript
复制
(((this->fbase) < true) > 5)

这是无稽之谈。template关键字显式地消除了这种歧义。将template关键字添加到您提到的其他情况中应该可以解决这些问题。

我实际上不确定为什么这对直接基类有效,所以如果有人能回答这部分问题,我很想看看答案是什么。

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4929869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档