Наследование от класса-шаблона с типом, определенным в производном классе.C++

Программы на C++. Форум разработчиков
Ответить Пред. темаСлед. тема
Гость
 Наследование от класса-шаблона с типом, определенным в производном классе.

Сообщение Гость »


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]
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C++»