模板类上的类型继承[重复]

问题描述 投票:1回答:1

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

但是如果没有定义myecho,它会编译并执行(在子类中不使用回调)

我已经尝试过了:

  • 没有定义int myecho(T arg,callback cbk)
  • 使用范围int myecho(T arg,Foo :: callback cbk)int myecho(T arg,Foo :: callback cbk)
  • 使用Foo :: callback使用sintax;
#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;
}
c++ templates inheritance using
1个回答
1
投票

你可以把它写成

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.