Skip to content

Instantly share code, notes, and snippets.

@aiekick
Last active December 15, 2024 23:39
Show Gist options
  • Select an option

  • Save aiekick/353290a6de18b71bdefe3bb6edc5d486 to your computer and use it in GitHub Desktop.

Select an option

Save aiekick/353290a6de18b71bdefe3bb6edc5d486 to your computer and use it in GitHub Desktop.

Revisions

  1. aiekick revised this gist Dec 15, 2024. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion baseIInternalDatasDerivation.cpp
    Original file line number Diff line number Diff line change
    @@ -18,7 +18,7 @@ class Node {
    explicit Node(const Datas& vDatas) : mp_datas(std::make_shared<Datas>(vDatas)) {}
    explicit Node(std::shared_ptr<Datas> vDatas) : mp_datas(std::move(vDatas)) {}

    // enable_if_t remove the need to use a slow dynamic_cast
    // enable_if remove the need to use a slow dynamic_cast
    template <typename T, typename = std::enable_if<std::is_base_of_v<Datas, T>>>
    const T& getDatas() const {
    return static_cast<const T&>(*mp_datas);
  2. aiekick renamed this gist Dec 15, 2024. 1 changed file with 0 additions and 0 deletions.
  3. aiekick created this gist Dec 15, 2024.
    50 changes: 50 additions & 0 deletions baseIInternalDatasDerivation
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    #include <iostream>
    #include <cassert>
    #include <memory>
    #include <string>

    struct Datas {
    std::string name;
    Datas() = default;
    explicit Datas(const std::string& vName) : name(vName) {}
    virtual ~Datas() = default;
    };

    class Node {
    std::shared_ptr<Datas> mp_datas;

    public:
    Node() = default;
    explicit Node(const Datas& vDatas) : mp_datas(std::make_shared<Datas>(vDatas)) {}
    explicit Node(std::shared_ptr<Datas> vDatas) : mp_datas(std::move(vDatas)) {}

    // enable_if_t remove the need to use a slow dynamic_cast
    template <typename T, typename = std::enable_if<std::is_base_of_v<Datas, T>>>
    const T& getDatas() const {
    return static_cast<const T&>(*mp_datas);
    }
    };

    struct NewDatas : public Datas {
    std::string type;
    NewDatas() = default;
    explicit NewDatas(const std::string& vName, const std::string& vType)
    : Datas(vName), type(vType) {}
    };

    class NewNode : public Node {
    public:
    NewNode() = default;

    template <typename T, typename = std::enable_if<std::is_base_of_v<Datas, T>>>
    explicit NewNode(const T& vDatas)
    : Node(std::make_shared<T>(vDatas)) {}
    };

    int main() {
    NewNode node(NewDatas("test", "read"));
    assert(node.getDatas<Datas>().name == "test");
    assert(node.getDatas<NewDatas>().name == "test");
    assert(node.getDatas<NewDatas>().type == "read");
    return EXIT_SUCCESS;
    }