fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3. #include <type_traits>
  4.  
  5. template <typename T>
  6. void deduce_type()
  7. {}
  8.  
  9.  
  10. class any
  11. {
  12. /*
  13.   template <typename T, typename ... Args>
  14.   any(Args&& ... args)
  15.   : ptr_(new T(std::forward<Args>(args) ...), std::default_delete<T>())
  16.   {}
  17.   */
  18.  
  19. public:
  20.  
  21. template <typename T>
  22. any(T&& other)
  23. : ptr_(new T(std::forward<T>(other))),
  24. deduce_type_(&deduce_type<T>)
  25. {}
  26.  
  27. template <typename T>
  28. bool contains_type() const
  29. {
  30. auto cc = deduce_type<T>;
  31. return deduce_type_ == cc;
  32. }
  33.  
  34. private:
  35. // std::unique_ptr<void, std::default_delete<void>> ptr_;
  36. void* ptr_;
  37. void(*deduce_type_)();
  38.  
  39. };
  40.  
  41. struct Foo
  42. {
  43.  
  44. };
  45.  
  46.  
  47. int main()
  48. {
  49.  
  50. any anyInt = 16;
  51. any anyInt2 = 17;
  52. any anyDouble = 2.0;
  53. any anyFoo = Foo();
  54.  
  55.  
  56. bool isInt = anyInt.contains_type<int>(),
  57. isInt2 = anyInt2.contains_type<int>(),
  58. notDouble = anyInt.contains_type<double>(), // 0 expected
  59. isDouble = anyDouble.contains_type<double>(),
  60. isFoo = anyFoo.contains_type<Foo>(),
  61. notFoo = anyInt.contains_type<Foo>(); // 0 expected
  62.  
  63. std::cout << "is int = " << isInt << std::endl;
  64. std::cout << "is int = " << isInt2 << std::endl;
  65. std::cout << "is not double = " << notDouble << std::endl;
  66. std::cout << "is double = " << isDouble << std::endl;
  67. std::cout << "is Foo = " << isFoo << std::endl;
  68. std::cout << "is not Foo = " << notFoo << std::endl;
  69.  
  70. return 0;
  71. }
Success #stdin #stdout 0s 4964KB
stdin
Standard input is empty
stdout
is int = 1
is int = 1
is not double = 0
is double = 1
is Foo = 1
is not Foo = 0