Last active
December 15, 2024 23:39
-
-
Save aiekick/353290a6de18b71bdefe3bb6edc5d486 to your computer and use it in GitHub Desktop.
base internal datas derivation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment