Advertisement
ReallyMatrix

C++ Question of the Day

Dec 19th, 2014
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. C++11 Quiz ( Type Traits )
  2. =======================
  3. Let's say I have the following piece of code.
  4.  
  5. #include <iostream>
  6.  
  7. struct Mom
  8. {
  9. virtual void play_strategy() const
  10. {
  11. std::cout << "Watching television" << std::endl;
  12. }
  13. virtual ~Mom() { }
  14. };
  15.  
  16. struct FemaleChild: Mom
  17. {
  18. virtual void play_strategy() const override
  19. {
  20. std::cout << "Playing with dolls" << std::endl;
  21. }
  22. };
  23.  
  24. struct MaleChild: Mom
  25. {
  26. virtual void play_strategy() const override
  27. {
  28. std::cout << "Kicking football around" << std::endl;
  29. }
  30. };
  31. struct UnrelatedWitchMom
  32. {
  33. void play_strategy() const
  34. {
  35. std::cout << "Killing innocent children" << std::endl;
  36. }
  37. };
  38.  
  39. int main()
  40. {
  41. Mom my_mom {};
  42. Mom *you = new FemaleChild{}, *me = new MaleChild{};
  43.  
  44. play_type( &my_mom );
  45. play_type( you );
  46. play_type( me );
  47.  
  48. UnrelatedWitchMom mom_ah {};
  49. play_type( &mom_ah );
  50.  
  51. delete you;
  52. delete me;
  53.  
  54. return 0;
  55. }
  56.  
  57. In C++, I know that I can make a template function that accepts any class object, like:
  58. template <class T> void iAcceptAnything(T x)
  59. {
  60. ....// Do something
  61. }
  62. Now, this works nice, but I would like to make a more restrict template class, something that ACCEPTs as T any type that INHERITs from class 'Mom'. What I would need is something like:
  63. template <class T:mom> void play_type(T *x)
  64. {
  65. x->play_strategy(); //or by reference, x.play_strategy();
  66. }
  67. Is this possible at all? If yes, how?
  68. Note that function 'play_type' has been intentionally left out, that's your task!
  69. Have fun!!!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement