fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <string>
  4.  
  5.  
  6. struct IHandle {
  7. virtual ~IHandle(void) {}
  8. virtual std::string const & GetName(void) const = 0;
  9. };
  10.  
  11.  
  12. template <typename T> struct Handle : IHandle {
  13. explicit Handle(std::shared_ptr<T> const & body) : mBody(body) {}
  14. std::string const & GetName(void) const { return mBody->GetName(); }
  15. private:
  16. std::shared_ptr<T> mBody;
  17. };
  18.  
  19.  
  20. struct IFoo {
  21. virtual ~IFoo(void) {}
  22. template <typename T> void NVMethod(std::shared_ptr<T> const & body) {
  23. VMethod(Handle<T>(body));
  24. }
  25. protected:
  26. virtual void VMethod(IHandle const & handle) = 0;
  27. };
  28.  
  29.  
  30. struct FooEx1 : IFoo {
  31. protected:
  32. void VMethod(IHandle const & handle) {
  33. std::cout << "引数の名前は " << handle.GetName() << " です。" << std::endl;
  34. }
  35. };
  36.  
  37.  
  38. struct FooEx2 : IFoo {
  39. protected:
  40. void VMethod(IHandle const & handle) {
  41. std::cout << "The name of argument is " << handle.GetName() << "." << std::endl;
  42. }
  43. };
  44.  
  45.  
  46. struct Argument1 {
  47. Argument1(std::string const & name) : mName(name) { }
  48. std::string const & GetName(void) const {
  49. return mName;
  50. }
  51. private:
  52. std::string mName;
  53. };
  54.  
  55.  
  56. struct Argument2 {
  57. Argument2(std::string const & name = std::string()) : mName(name) { }
  58. std::string const & GetName(void) const {
  59. static std::string const anon("Anon");
  60. return mName.empty() ? anon : mName;
  61. }
  62. private:
  63. std::string mName;
  64. };
  65.  
  66.  
  67. int main(void) {
  68. std::shared_ptr<IFoo> p;
  69.  
  70. p = std::make_shared<FooEx1>();
  71. p->NVMethod(std::make_shared<Argument1>("Bob"));
  72.  
  73. p = std::make_shared<FooEx2>();
  74. p->NVMethod(std::make_shared<Argument2>());
  75.  
  76. return 0;
  77. }
  78.  
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
引数の名前は Bob です。
The name of argument is Anon.