I want to inherit from a template class with a type defined in the derived class. I dont want to use composition because if I do so, I have to give public access to the vector or write some methods for each object in order to interact with the vector the way I want to.
Is there any way to make this code work ?
(Ok I just have to declare my struct before the class like in 1) commented example, but I am interesting to know is there some hack to do it like this...)
Код: Выделить всё
#include
#include
class Interface
{
public:
virtual void populate() = 0;
};
template
class Series : Interface
{
public:
T methodIwantToWriteOnce(int i) const { return mVec[i]; }
protected:
std::vector mVec;
};
class SeriesInt : public Series
{
public:
virtual void populate() override { mVec.push_back(42); }
};
/* 1) Working solution but outside the class */
// struct Coord
// {
// double x = 0.0;
// double y = 0.0;
// };
// class SeriesCoord : public Series
// {
// public:
// virtual void populate() override { mVec.push_back({42.0, 42.0}); }
// };
/* 2) Impossible solution ? */
// Forward declaration
class SeriesCoord;
struct SeriesCoord::Coord; //useless I know but you see the idea
class SeriesCoord : public Series
{
public:
struct Coord
{
double x = 0.0;
double y = 0.0;
};
virtual void populate() override { mVec.push_back({42.0, 42.0}); }
};
int main(int argc, char *argv[])
{
SeriesInt s1;
s1.populate();
std::cout
Источник: [url]https://stackoverflow.com/questions/78133053/inheritance-from-template-class-with-a-type-defined-in-the-derivated-class[/url]