Last active
December 15, 2024 23:39
-
-
Save aiekick/353290a6de18b71bdefe3bb6edc5d486 to your computer and use it in GitHub Desktop.
Revisions
-
aiekick revised this gist
Dec 15, 2024 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
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 charactersOriginal 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 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); -
aiekick renamed this gist
Dec 15, 2024 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
aiekick created this gist
Dec 15, 2024 .There are no files selected for viewing
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 charactersOriginal 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; }