fork(1) download
  1. #include <functional>
  2. #include <iostream>
  3. #include <cassert>
  4.  
  5. int foo(double d) { return d; }
  6.  
  7. double bar(double d) { return 2*d; }
  8.  
  9. struct Result {
  10. union {
  11. int i_res;
  12. double d_res;
  13. };
  14. enum { IS_INT, IS_DOUBLE } u_tag;
  15.  
  16. Result(Result const&) = default;
  17. Result(int i) : i_res{i}, u_tag{IS_INT} {}
  18. Result(double d) : d_res{d}, u_tag{IS_DOUBLE} {}
  19.  
  20. Result& operator=(Result const&) = default;
  21. auto& operator=(int i)
  22. { i_res = i; u_tag = IS_INT; return *this; }
  23. auto& operator=(double d)
  24. { d_res = d; u_tag = IS_DOUBLE; return *this; }
  25. };
  26.  
  27. int main() {
  28. std::function<Result(double)> cb;
  29.  
  30. cb = foo;
  31. auto r = cb(1.0);
  32. assert(r.u_tag == Result::IS_INT);
  33. std::cout << r.i_res << '\n';
  34.  
  35. cb = bar;
  36. r = cb(2.0);
  37. assert(r.u_tag == Result::IS_DOUBLE);
  38. std::cout << r.d_res << '\n';
  39.  
  40. return 0;
  41. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
1
4