fork download
  1. #include <string>
  2. #include <iostream>
  3.  
  4. struct Foo {
  5. char c;
  6. void set(std::string s) {c = s[0];}; // We don't really care here
  7. };
  8. struct Bar {
  9. int n;
  10. void set(std::string s) {n = s.size();}; // We don't really care here
  11. };
  12.  
  13. template<typename T>
  14. struct Identified {
  15. T model;
  16. std::string id;
  17. };
  18.  
  19. template<typename T>
  20. Identified<T> GetIdentifiedModel(std::string id) {
  21. Identified<T> result;
  22. result.id = id;
  23. // Obviously shouldn't be ID but for the example
  24. result.model.set(id); // Common method for T
  25. return result;
  26. }
  27.  
  28. void assert(bool b) {
  29. if (b) std::cout << "OK" << std::endl;
  30. else std::cout << "There is a problem !" << std::endl;
  31. };
  32.  
  33. int main() {
  34. auto fooWithID = GetIdentifiedModel<Foo>("foo id");
  35. auto barWithID = GetIdentifiedModel<Bar>("bar");
  36. assert (fooWithID.model.c == 'f');
  37. assert (barWithID.model.n == 3);
  38. return (0);
  39. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
OK
OK