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

标签 c++ templates derived-class

下面是两种情况。

案例 1) Base->BaseIndirect->DerivedIndirect

情况 2)基础->派生

在案例 2) 中,我可以使用 3 种表示法调用基类的模板函数。 在案例 1) 中,我可以仅使用其中一种表示法来调用 Base 类的模板函数。而且,我无法使用任何符号调用 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 关键字添加到您提到的其他情况中应该可以解决这些问题。

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

关于C++调用基类的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4929869/

相关文章:

c++ - 带有模板基类的静态成员定义

C++ - 有一个类型能够容纳它的 child

c++ - 从派生类构造函数调用基类构造函数

c++ - recvfrom 与 INADDR_ANY 一起工作,但指定特定接口(interface)不起作用

c++ - std::function 如何知道调用约定?

c++ - 哪些库使用通过编译时元编程技术实现的设计模式?

c# - 表单设计器打破了通用抽象 UserControl

c++ - 分配的数组已归零

c++ - 如何知道给定的 DLL 是否被给定的进程加载?

c++ - std::vector 的表达式模板运算符重载问题