fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <exception>
  4. using namespace std;
  5.  
  6. ////////////////////////////////////////////////////////////////////////////////
  7.  
  8. template <class T>
  9. bool inspect(exception_ptr p, void (&fun)(T))
  10. {
  11. try
  12. {
  13. if (p != exception_ptr())
  14. rethrow_exception(p);
  15. }
  16. catch (T t)
  17. {
  18. fun(t);
  19. return true;
  20. }
  21. catch (...)
  22. {
  23. return false;
  24. }
  25. }
  26.  
  27. ////////////////////////////////////////////////////////////////////////////////
  28.  
  29. class printable
  30. {
  31. public:
  32. virtual void print() const = 0;
  33. };
  34.  
  35. ////////////////////////////////////////////////////////////////////////////////
  36.  
  37. class foo : public printable
  38. {
  39. public:
  40. foo(string const& s) : m_s(s) {}
  41.  
  42. virtual void print() const
  43. {
  44. cout << "foo: " << m_s << "\n";
  45. }
  46.  
  47. private:
  48. string m_s;
  49. };
  50.  
  51. class bar : public printable
  52. {
  53. public:
  54. bar(int i) : m_i(i) {}
  55.  
  56. virtual void print() const
  57. {
  58. cout << "bar: " << m_i << "\n";
  59. }
  60.  
  61. private:
  62. int m_i;
  63. };
  64.  
  65. ////////////////////////////////////////////////////////////////////////////////
  66.  
  67. void print_printable(printable& p)
  68. {
  69. p.print();
  70. }
  71.  
  72. ////////////////////////////////////////////////////////////////////////////////
  73.  
  74. int main()
  75. {
  76. auto f = make_exception_ptr(foo("foo"));
  77. auto b = make_exception_ptr(bar(42));
  78.  
  79. inspect(f, print_printable);
  80. inspect(b, print_printable);
  81.  
  82. return 0;
  83. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
foo: foo
bar: 42