Search code examples
c++templatesinheritanceusing

Inheritance of type on a template class


I am trying to make use of a type from a parent template class in the definition of a new function in a child class and I am not able to making it compile.

However it does compile and execute if myecho is not defined (callback not used in child class)

I have already tried:

  • No definition int myecho(T arg, callback cbk)

  • Using scope int myecho(T arg, Foo::callback cbk) int myecho(T arg, Foo::callback cbk)

  • using sintax using 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;
}

Solution

  • You can write it as

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

    Or introduce the name via using.

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