Skip to content

Instantly share code, notes, and snippets.

@yknishidate
Created October 28, 2023 06:02
Show Gist options
  • Save yknishidate/9752891e21e1abdc6191d88d3307d635 to your computer and use it in GitHub Desktop.
Save yknishidate/9752891e21e1abdc6191d88d3307d635 to your computer and use it in GitHub Desktop.
simple_class_factory
#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