【问题标题】:Inheritance of type on a template class [duplicate]模板类上的类型继承[重复]
【发布时间】:2019-09-02 21:31:40
【问题描述】:

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

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

我已经试过了:

  • 无定义 int myecho(T arg, 回调 cbk)

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

  • 使用 sintax 使用 Foo::callback;

#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】:

    你可以写成

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 2011-03-17
      • 2018-07-06
      • 1970-01-01
      • 2015-01-01
      相关资源
      最近更新 更多