fork download
  1. #include <iostream>
  2.  
  3. struct Var {
  4. char getChar() const { return 0; }
  5. int getInt() const { return 1; }
  6. float getFloat() const { return 1.1f; }
  7. double getDouble() const { return 1.11; }
  8. };
  9.  
  10. class Base {
  11. public:
  12. virtual void set(const Var &x) {};
  13. };
  14.  
  15. class SetImpl {
  16. protected:
  17. void set_impl(const Var &x, char &y) {
  18. y = x.getChar();
  19. }
  20. void set_impl(const Var &x, int &y) {
  21. y = x.getInt();
  22. }
  23. void set_impl(const Var &x, float &y) {
  24. y = x.getFloat();
  25. }
  26. void set_impl(const Var &x, double &y) {
  27. y = x.getDouble();
  28. }
  29. };
  30.  
  31. template <typename T>
  32. class Deriv : public Base, public SetImpl {
  33. T &v;
  34. public:
  35. Deriv(T &v) : v(v) {}
  36. virtual void set(const Var &x) {
  37. set_impl(x, v);
  38. };
  39. };
  40.  
  41. #include <vector>
  42. #include <memory>
  43.  
  44. using namespace std;
  45. int main(int argc, char *argv[]) {
  46. Var v;
  47. char c;
  48. int n;
  49. float f;
  50. double d;
  51.  
  52. vector<Base *> xs;
  53. xs.push_back(new Deriv<decltype(c)>(c));
  54. xs.push_back(new Deriv<decltype(n)>(n));
  55. xs.push_back(new Deriv<decltype(f)>(f));
  56. xs.push_back(new Deriv<decltype(d)>(d));
  57.  
  58. for(auto x : xs) {
  59. x->set(v);
  60. }
  61.  
  62. cout << (int)c << ", " << n << ", " << f << ", " << d << endl;
  63.  
  64. return EXIT_SUCCESS;
  65. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
0, 1, 1.1, 1.11