模板上的类型继承 class

Inheritance of type on a template class

我试图在子 class 的新函数定义中使用来自父模板 class 的类型,但我无法编译它。

但是,如果未定义 myecho(子 class 中未使用回调),它会编译并执行

我已经试过了:

#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;
}