fork(1) download
  1. #include <iostream>
  2. #include <typeinfo>
  3. using namespace std;
  4.  
  5. template <class T>
  6. struct traitFoo: public T {
  7. traitFoo():T(){}
  8. virtual ~traitFoo(){}
  9. virtual void foo()
  10. {
  11. cout << typeid(this).name() << " " << typeid(T).name() << " foo" << endl;
  12. cout << this->i << endl; // Раскомментируйте для боли - всё ок
  13. }
  14. };
  15.  
  16. struct baseStruct {};
  17. template <typename T>
  18. struct withi : baseStruct {T i;};
  19. struct bar : public withi<int>{};
  20. struct baz : public withi<float>{};
  21.  
  22. int main() {
  23. using BarFoo = traitFoo<bar>;
  24. using BazFoo = traitFoo<baz>;
  25.  
  26. BarFoo rfoo;
  27. rfoo.i = 1.5;
  28. BazFoo zfoo;
  29. zfoo.i = 1.5;
  30. rfoo.foo();
  31. zfoo.foo();
  32.  
  33. // Как сюда дабавить хранение BarFoo и BazFoo в общем массиве? - вроде норм
  34. baseStruct arr[2] = { rfoo, zfoo };
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
P8traitFooI3barE 3bar foo
1
P8traitFooI3bazE 3baz foo
1.5