fork download
  1. #include <iostream>
  2.  
  3. class any {
  4. public:
  5. template<class T>
  6. any(T const& i) : _erasure() {
  7. _erasure = new derive<T>(i);
  8. }
  9. any() = default;
  10.  
  11. template<class T>
  12. any& operator=(T const& i) {
  13. if(_erasure) {
  14. delete _erasure;
  15. }
  16. _erasure = new derive<T>(i);
  17. return *this;
  18. }
  19.  
  20. void call() const {
  21. _erasure->call();
  22. }
  23.  
  24. private:
  25. struct base {
  26. virtual ~base() {};
  27. virtual void call() =0;
  28. };
  29.  
  30. template<class U>
  31. struct derive : public base{
  32. U val;
  33. derive(U const& i) : val(i) {};
  34. void call() {
  35. val.call();
  36. }
  37. };
  38.  
  39. base* _erasure;
  40. };
  41.  
  42. struct hoge {
  43. void call() const { std::cout << "hoge::call" << std::endl; }
  44. };
  45.  
  46. struct foo {
  47. void call() const { std::cout << "foo::call" << std::endl; }
  48. };
  49.  
  50. int main() {
  51. any val;
  52.  
  53. val = hoge();
  54. val.call();
  55.  
  56. val = foo();
  57. val.call();
  58. }
Success #stdin #stdout 0s 2960KB
stdin
Standard input is empty
stdout
hoge::call
foo::call