模板类上的类型继承

Inheritance of type on a template class

本文关键字:类型 继承      更新时间:2023-10-16

我正在尝试在子类中的新函数定义中使用父模板类中的类型,但我无法对其进行编译。

但是,如果未定义myecho,它确实会编译和执行(子类中未使用回调(

我已经尝试过:

  • 无定义int myecho(T arg, callback cbk(

  • 使用范围int myecho(T arg, Foo::callback cbk(int myecho(T arg, Foo::callback cbk(

  • 使用辛税使用 Foo::回调;

#include <cstdio>
#include <iostream>
#include <functional>
template <class T>
class Foo
{
public:
  using callback = std::function<int (T param)>;
  Foo() = default;
  virtual ~Foo() = default;
  int echo(T arg, callback cbk) { return cbk(arg);}
};
template <class T>
class _FooIntImp : public Foo<T>
{
public:
  using Foo<T>::echo;
  _FooIntImp() = default;
  virtual ~_FooIntImp() = default;
  int myecho(T arg, callback cbk)
  {
    return 8;
  }
};
using FooInt = _FooIntImp<int>;
int mycallback( int param )
{
  return param * param;
}
int main(int argc, char* argv[] )
{
  FooInt l_foo;
  std::cout << "Out "<<l_foo.echo(43,mycallback) << std::endl;
  return 0;
}

你可以把它写成

int myecho(T arg, typename Foo<T>::callback cbk)
//                ^^^^^^^^^^^^^^^^^
{
  return 8;
}

或通过using介绍名称。

using typename Foo<T>::callback;
int myecho(T arg, callback cbk)
{
  return 8;
}