Use template class before specifying it
For some reason, I need to return the value as a template class specified by type. But the problem is that the template class inherits from the non-template class, which has a method, returns the value of the template class specified in the type.
It should be like this:
class Base
{
// ...
_Int Foo() = 0;
};
template<typename T>
class Derived
: public Base
{
public:
// ...
_Int Foo() override
{
// ...
}
};
typedef Derived<int> _Int;
So my question is, is there a way that can help me use the specified template class type before it is defined?
To declare the return type of a function, you don't need a type definition, just a declaration. This means that you can do this:
template <class T>
class Derived;
typedef Derived<int> _Int;
class Base
{
// ...
virtual _Int Foo() = 0;
};
template<typename T>
class Derived
: public Base
{
public:
// ...
_Int Foo() override
{
// ...
}
};
[Live example]
Two side notes unrelated to the question:
-
Your code was missing
virtual
from the declarationFoo
. -
Any name beginning with an underscore followed by an uppercase letter is reserved for the C ++ implementation (compiler and standard library) and should not be used in user code. You must change the name
_Int
to something else.Names that contain two consecutive underscores are also reserved, and names beginning with an underscore are reserved in the global scope.
This is an instance of a curiously repeating template template that can be used by passing a derived class as a template parameter to the base class
template<typename Int>
class Base
{
// ...
virtual Int Foo() = 0;
};
and then passing it explicitly on inheritance:
template<typename T>
class Derived
: public Base<Derived<T>>
{
public:
// ...
Derived<T> Foo() override
{
// ...
}
};