Guest User

Untitled

a guest
Jan 24th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. void foo()
  4. {
  5. std::cout << "foo" << std::endl;
  6. }
  7.  
  8. void bar(int x)
  9. {
  10. std::cout << "bar" << std::endl;
  11. }
  12.  
  13. // template traits class
  14. template<class F>
  15. struct function_traits;
  16.  
  17. // specialization using function pointer
  18. template<class... Args>
  19. struct function_traits<void (*)(Args...)>
  20. {
  21. static constexpr std::size_t number_parameters = sizeof...(Args);
  22. };
  23.  
  24. template <typename Func>
  25. void call(Func f)
  26. {
  27. if constexpr (function_traits<Func>::number_parameters == 0)
  28. f();
  29. else
  30. f(0);
  31. }
  32.  
  33. // Old way
  34. template <typename Func,
  35. typename std::enable_if_t<
  36. function_traits<Func>::number_parameters == 0>* = nullptr>
  37. void call_old(Func f)
  38. {
  39. f();
  40. }
  41.  
  42. template <typename Func,
  43. typename std::enable_if_t<
  44. function_traits<Func>::number_parameters == 1>* = nullptr>
  45. void call_old(Func f)
  46. {
  47. f(0);
  48. }
  49.  
  50. int main()
  51. {
  52. call(foo);
  53. call(bar);
  54.  
  55. call_old(foo);
  56. call_old(bar);
  57. return 0;
  58. }
Add Comment
Please, Sign In to add comment