-1

Я хочу сделать класс BaseNode и несколько классов-наследников (NodeElement:BaseNode, RenderableNode:BaseNode, UIElement:RenderableNode, Image:UIElement и Text:UIElement)

У BaseNode есть функция getChildren(), которая должна вернуть std::variant<NodeElement, RenderableNode, UIElement, Image, Text>, но для компилятора классы в std::variantе на момент объявления BaseNode ещё не заданы

Я пробовал поместить BaseNode после остальных классов, но получал ошибку, так как они наследуют BaseNode

Вот упрощённый код .hh файла (не важные участки кода закомментированы):

#pragma once

/*#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>*/
#include <vector>
#include <variant>

#define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>

class BaseNode {
private:
    std::vector<NodeI> _children;
/*    bool _freed;

    void _checkIsFreed();
    void _customFree();*/

public:
    BaseNode();

//    bool isFreed();
    std::vector<NodeI> getChildren() const;
//    unsigned long long getChildCount();
    void addChild(NodeI);
//    void removeChild(unsigned long long);
//    void free();
};

class NodeElement : public BaseNode {
//private:
//    void _customFree();
};

class RenderableNode : public BaseNode {
//public:
//    bool visible = true;
};

class UIElement : public RenderableNode {
/*private:
    void _customFree();

public:
    int position[2] = {0, 0};
    int size[2] = {0, 0};
    SDL_Texture *texture = NULL;

    void changeTexture(SDL_Texture*);*/
};

class Image : public UIElement {};

class Text : public UIElement {
/*private:
    char *_text = (char*) "";
    bool _isTextChanged = false;

public:
    TTF_Font *font;
    SDL_Color color;

    void setText(char*);
    void setTextTexture(SDL_Texture*);
    bool getTextChanged();
    char *getText();*/
};

Как сделать функцию getChildren() в .cc файле я знаю, но как всё правильно сделать в .hh файле, чтобы не было ошибок компилятора?

Также я не хочу слишком усложнять код, добавляя полиморфизм, или другие сложные реализации

Вывод компилятора:

97:28: error: 'NodeElement' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                            ^~~~~~~~~~~
101:17: note: in expansion of macro 'NodeI'
  101 |     std::vector<NodeI> _children;
      |                 ^~~~~
97:41: error: 'RenderableNode' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                         ^~~~~~~~~~~~~~
101:17: note: in expansion of macro 'NodeI'
  101 |     std::vector<NodeI> _children;
      |                 ^~~~~
97:57: error: 'UIElement' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                         ^~~~~~~~~
101:17: note: in expansion of macro 'NodeI'
  101 |     std::vector<NodeI> _children;
      |                 ^~~~~
97:68: error: 'Image' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                    ^~~~~
101:17: note: in expansion of macro 'NodeI'
  101 |     std::vector<NodeI> _children;
      |                 ^~~~~
97:75: error: 'Text' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                           ^~~~
101:17: note: in expansion of macro 'NodeI'
  101 |     std::vector<NodeI> _children;
      |                 ^~~~~
97:79: error: template argument 1 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
101:17: note: in expansion of macro 'NodeI'
  101 |     std::vector<NodeI> _children;
      |                 ^~~~~
97:79: error: template argument 2 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
101:17: note: in expansion of macro 'NodeI'
  101 |     std::vector<NodeI> _children;
      |                 ^~~~~
97:79: error: template argument 3 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
101:17: note: in expansion of macro 'NodeI'
  101 |     std::vector<NodeI> _children;
      |                 ^~~~~
97:79: error: template argument 4 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
101:17: note: in expansion of macro 'NodeI'
  101 |     std::vector<NodeI> _children;
      |                 ^~~~~
97:79: error: template argument 5 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
101:17: note: in expansion of macro 'NodeI'
  101 |     std::vector<NodeI> _children;
      |                 ^~~~~
101:22: error: template argument 1 is invalid
  101 |     std::vector<NodeI> _children;
      |                      ^
101:22: error: template argument 2 is invalid
97:28: error: 'NodeElement' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                            ^~~~~~~~~~~
111:17: note: in expansion of macro 'NodeI'
  111 |     std::vector<NodeI> getChildren() const;
      |                 ^~~~~
97:41: error: 'RenderableNode' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                         ^~~~~~~~~~~~~~
111:17: note: in expansion of macro 'NodeI'
  111 |     std::vector<NodeI> getChildren() const;
      |                 ^~~~~
97:57: error: 'UIElement' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                         ^~~~~~~~~
111:17: note: in expansion of macro 'NodeI'
  111 |     std::vector<NodeI> getChildren() const;
      |                 ^~~~~
97:68: error: 'Image' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                    ^~~~~
111:17: note: in expansion of macro 'NodeI'
  111 |     std::vector<NodeI> getChildren() const;
      |                 ^~~~~
97:75: error: 'Text' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                           ^~~~
111:17: note: in expansion of macro 'NodeI'
  111 |     std::vector<NodeI> getChildren() const;
      |                 ^~~~~
97:79: error: template argument 1 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
111:17: note: in expansion of macro 'NodeI'
  111 |     std::vector<NodeI> getChildren() const;
      |                 ^~~~~
97:79: error: template argument 2 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
111:17: note: in expansion of macro 'NodeI'
  111 |     std::vector<NodeI> getChildren() const;
      |                 ^~~~~
97:79: error: template argument 3 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
111:17: note: in expansion of macro 'NodeI'
  111 |     std::vector<NodeI> getChildren() const;
      |                 ^~~~~
97:79: error: template argument 4 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
111:17: note: in expansion of macro 'NodeI'
  111 |     std::vector<NodeI> getChildren() const;
      |                 ^~~~~
97:79: error: template argument 5 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
111:17: note: in expansion of macro 'NodeI'
  111 |     std::vector<NodeI> getChildren() const;
      |                 ^~~~~
111:22: error: template argument 1 is invalid
  111 |     std::vector<NodeI> getChildren() const;
      |                      ^
111:22: error: template argument 2 is invalid
97:28: error: 'NodeElement' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                            ^~~~~~~~~~~
113:19: note: in expansion of macro 'NodeI'
  113 |     void addChild(NodeI);
      |                   ^~~~~
97:41: error: 'RenderableNode' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                         ^~~~~~~~~~~~~~
113:19: note: in expansion of macro 'NodeI'
  113 |     void addChild(NodeI);
      |                   ^~~~~
97:57: error: 'UIElement' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                         ^~~~~~~~~
113:19: note: in expansion of macro 'NodeI'
  113 |     void addChild(NodeI);
      |                   ^~~~~
97:68: error: 'Image' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                    ^~~~~
113:19: note: in expansion of macro 'NodeI'
  113 |     void addChild(NodeI);
      |                   ^~~~~
97:75: error: 'Text' was not declared in this scope
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                           ^~~~
113:19: note: in expansion of macro 'NodeI'
  113 |     void addChild(NodeI);
      |                   ^~~~~
97:79: error: template argument 1 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
113:19: note: in expansion of macro 'NodeI'
  113 |     void addChild(NodeI);
      |                   ^~~~~
97:79: error: template argument 2 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
113:19: note: in expansion of macro 'NodeI'
  113 |     void addChild(NodeI);
      |                   ^~~~~
97:79: error: template argument 3 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
113:19: note: in expansion of macro 'NodeI'
  113 |     void addChild(NodeI);
      |                   ^~~~~
97:79: error: template argument 4 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
113:19: note: in expansion of macro 'NodeI'
  113 |     void addChild(NodeI);
      |                   ^~~~~
97:79: error: template argument 5 is invalid
   97 | #define NodeI std::variant<NodeElement, RenderableNode, UIElement, Image, Text>
      |                                                                               ^
113:19: note: in expansion of macro 'NodeI'
  113 |     void addChild(NodeI);
      |                   ^~~~~
2
  • 1
    Полиморфизм не усложняет код, а делает его проще. Вы хотите сложную вещь сделать просто, но в данном случае это не получится. Возможно, вам просто нужно пересмотреть концепцию 16 окт 2022 в 9:29
  • 2
    Полиморфизм сделал бы этот код кратким и понятным. Вы же пытаетесь убрать из С++ одну из самых сильных сторон, заменив ее весьма странным и, как по мне, дорогостоящим костылем. Добавление еще одного потомка заставит кардинально переписывать весь такой код — во имя чего?
    – Harry
    16 окт 2022 в 9:55

1 ответ 1

-1

Вы можете оттолкнуться от этого варианта, однако, от динамического полиморфизма не очень далеко уйдете: все равно нужно смотреть типы и т.п

#include <vector>
#include <variant>
#include <iostream>
#include <type_traits>

class NodeElement;
class RenderableNode;
class UIElement;
class Image;
class Text;

class BaseNode
{
public:
    using NodeTy = std::variant<NodeElement, RenderableNode, UIElement, Image, Text>;

    virtual ~BaseNode() = default;

    const std::vector<NodeTy>& getChildren() const
    {
        return _childrens;
    }

    void addChild(const NodeTy& node)
    {
        _childrens.push_back(node);
    }

private:
    std::vector<NodeTy> _childrens;
};

class NodeElement : public BaseNode
{
public:
    NodeElement(int ne):
        _ne(ne)
    {
    }

    decltype(auto) getNe() const noexcept
    {
        return _ne;
    }

private:
    int _ne;
};

class RenderableNode : public BaseNode
{
public:
    RenderableNode(const std::string& rn):
        _rn(rn)
    {
    }

    decltype(auto) getRn() const noexcept
    {
        return _rn;
    }

private:
    std::string _rn;
};

class UIElement : public RenderableNode
{
public:
    UIElement(const char* uie, bool flag):
        RenderableNode(uie),
        _flag(flag)
    {
    }

    decltype(auto) getFlag() const noexcept
    {
        return _flag;
    }

private:
    bool _flag;
};

class Image : public UIElement
{
public:
    Image(int value, const char* uie, bool flag):
        UIElement(uie, flag),
        _value(value)
    {
    }

    decltype(auto) getValue() const noexcept
    {
        return _value;
    }

private:
    int _value;
};

class Text : public UIElement
{
public:
    Text(const std::string& text, const char* uie, bool flag):
        UIElement(uie, flag),
        _text(text)
    {
    }

    decltype(auto) getText() const noexcept
    {
        return _text;
    }

private:
    std::string _text;
};

int main()
{
    BaseNode base;
    base.addChild(NodeElement(1));
    base.addChild(RenderableNode("second child"));
    base.addChild(UIElement("third child", false));
    base.addChild(Image(4, "fourth child", true));
    base.addChild(Text("fifth child", "string for parent", false));

    for (const auto& child : base.getChildren())
    {
        std::visit([](const auto& var){
            if constexpr (std::is_same<typename std::decay<decltype(var)>::type, BaseNode>::value)
            {
                std::cout << "BaseNode";
            }
            else if constexpr (std::is_same<typename std::decay<decltype(var)>::type, NodeElement>::value)
            {
                std::cout << "NodeElement(ne: " << var.getNe() << ')';
            }
            else if constexpr (std::is_same<typename std::decay<decltype(var)>::type, RenderableNode>::value)
            {
                std::cout << "RenderableNode(rn: " << var.getRn() << ")";
            }
            else if constexpr (std::is_same<typename std::decay<decltype(var)>::type, UIElement>::value)
            {
                std::cout << "UIElement(rn: " << var.getRn() << ", flag: " << var.getFlag() << ")";
            }
            else if constexpr (std::is_same<typename std::decay<decltype(var)>::type, Image>::value)
            {
                std::cout << "Image(rn: " << var.getRn() << ", flag:" << var.getFlag() << ", value: " << var.getValue() << ")";
            }
            else if constexpr (std::is_same<typename std::decay<decltype(var)>::type, Text>::value)
            {
                std::cout << "Text(rn: " << var.getRn() << ", flag: " << var.getFlag() << ", text: " << var.getText() << ")";
            }
            std::cout << '\n';
        }, child);
    }
    return 0;
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.