fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <memory>
  4. #include <vector>
  5. #include <type_traits>
  6.  
  7. struct IFactory {
  8. typedef std::shared_ptr<IFactory> SharedFactory;
  9. virtual std::string Name() {
  10. return "IFactory";
  11. }
  12. template<class... Arg>
  13. SharedFactory Dup(const Arg&... A) {
  14. return std::make_shared<std::remove_reference<decltype(*this)>::type>(A...);
  15. }
  16. enum {
  17. ClassIFactory, ClassA, ClassB,
  18. };
  19. bool Say() {
  20. std::cout << "Hoge" << X << std::endl;
  21. return true;
  22. }
  23. int X = 123;
  24. IFactory() {
  25. std::cout << "IFactory() called. X=" << X << std::endl;
  26. }
  27. };
  28.  
  29. class A : public IFactory {
  30. public:
  31. std::string Name() {
  32. return "A";
  33. }
  34. bool Say() {
  35. std::cout << "Baw" << X << std::endl;
  36. return true;
  37. }
  38. int X = 0;
  39. A() {
  40. std::cout << "A() called. X=" << X << std::endl;
  41. }
  42. };
  43.  
  44. class B : public IFactory {
  45. public:
  46. std::string Name() {
  47. return "B";
  48. }
  49. bool Say() {
  50. std::cout << "Maw" << X << std::endl;
  51. return true;
  52. }
  53. char X = 0;
  54. B() {
  55. std::cout << "B() called. X=" << X << std::endl;
  56. }
  57. };
  58.  
  59. typedef std::vector<IFactory::SharedFactory> FType;
  60.  
  61. FType MakeVector() {
  62. FType F = { std::make_shared<IFactory>(), std::make_shared<A>(), std::make_shared<B>() };
  63.  
  64. return F;
  65. }
  66.  
  67. int main()
  68. {
  69. FType F = MakeVector();
  70.  
  71. auto X = F[IFactory::ClassIFactory]->Dup();
  72.  
  73. std::cout << X->Name() << std::endl;
  74. std::cout << X->Say() << std::endl;
  75.  
  76. A* AA = static_cast<A*>(&(*X));
  77.  
  78. std::cout << AA->Name() << std::endl;
  79. std::cout << AA->Say() << std::endl;
  80. }
  81.  
Success #stdin #stdout 0s 4560KB
stdin
Standard input is empty
stdout
IFactory() called. X=123
IFactory() called. X=123
A() called. X=0
IFactory() called. X=123
B() called. X=
IFactory() called. X=123
IFactory
Hoge123
1
IFactory
Baw0
1