fork download
  1. #include <iostream>
  2.  
  3. // Declared but not defined, specializations will provide definitions
  4. template<typename T>
  5. struct GenericTypeTraits;
  6.  
  7. template<typename T>
  8. class Generic
  9. {
  10. public:
  11. using IdType = typename GenericTypeTraits<T>::IdType;
  12.  
  13. void setIdentifier(IdType id)
  14. {
  15. mType.mIdentifier = id;
  16. }
  17.  
  18. IdType getIdentifier() const
  19. {
  20. return mType.mIdentifier;
  21. }
  22.  
  23. private:
  24. T mType;
  25. };
  26.  
  27. class Type1
  28. {
  29. public:
  30. int mIdentifier;
  31. };
  32.  
  33. template<>
  34. struct GenericTypeTraits<Type1>
  35. {
  36. using IdType = int;
  37. };
  38.  
  39. class Type2
  40. {
  41. public:
  42. std::string mIdentifier;
  43. };
  44.  
  45. template<>
  46. struct GenericTypeTraits<Type2>
  47. {
  48. using IdType = std::string;
  49. };
  50.  
  51. int main()
  52. {
  53. Generic<Type1> t1[5];
  54. t1[0].setIdentifier(3);
  55. std::cout << t1[0].getIdentifier() << "\n";
  56.  
  57. Generic<Type2> t2[5];
  58. t2[0].setIdentifier("3");
  59. std::cout << t2[0].getIdentifier() << "\n";
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
3
3