Created
October 28, 2023 06:02
-
-
Save yknishidate/9752891e21e1abdc6191d88d3307d635 to your computer and use it in GitHub Desktop.
simple_class_factory
This file contains 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 <vector> | |
#include <iostream> | |
#include <functional> | |
#include <unordered_map> | |
using namespace std; | |
struct Base{ virtual void print() = 0; }; | |
struct A : public Base{ void print() override { cout << "A" << endl; } }; | |
struct B : public Base{ void print() override { cout << "B" << endl; } }; | |
struct C : public Base{ void print() override { cout << "C" << endl; } }; | |
Base* createA(){ return new A(); } | |
Base* createB(){ return new B(); } | |
Base* createC(){ return new C(); } | |
int main() | |
{ | |
vector<Base*> v; | |
unordered_map<char, function<Base*(void)>> funcs{ | |
{'A', createA}, | |
{'B', createB}, | |
{'C', createC}, | |
}; | |
while(true){ | |
char input; | |
cin >> input; | |
if(funcs.contains(input)){ | |
Base* newPtr = funcs[input](); | |
v.push_back(newPtr); | |
}else if(input == 'q'){ | |
break; | |
} | |
} | |
cout << "--- vector ---" << endl; | |
for(auto& e: v){ | |
e->print(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment