fork download
  1. #include <iostream>
  2.  
  3. struct shared_buffer {};
  4.  
  5. shared_buffer do_pack(int arg);
  6. shared_buffer do_pack(double arg);
  7.  
  8. struct foo {
  9. friend shared_buffer do_pack(foo const& arg);
  10. };
  11.  
  12.  
  13. struct somestruct {
  14. template<typename... Args>
  15. shared_buffer pack(const Args&... args) {
  16. // convert arg pack to array of pack functions and arguments
  17. arg_pack_fn fns[] = { &wrap_do_pack<Args>... };
  18. void const* data[] = { std::addressof(args)... };
  19.  
  20. return pack2(fns, data, sizeof...(Args));
  21. }
  22.  
  23. private:
  24. using arg_pack_fn = shared_buffer (*)(void const* arg);
  25.  
  26. // actual do_pack for each arg type
  27. template<typename T>
  28. static shared_buffer wrap_do_pack(void const* arg) {
  29. return do_pack(*static_cast<T const*>(arg));
  30. }
  31.  
  32. shared_buffer pack2(arg_pack_fn pack_fns[], void const* args[], size_t count);
  33. };
  34.  
  35. // implementation in .cpp
  36.  
  37. shared_buffer do_pack(int arg) {
  38. std::cout << arg << ' ';
  39. }
  40.  
  41. shared_buffer do_pack(double arg) {
  42. std::cout << arg << ' ';
  43. }
  44.  
  45. shared_buffer do_pack(foo const& arg) {
  46. std::cout << "foo ";
  47. }
  48.  
  49. shared_buffer somestruct::pack2(arg_pack_fn pack_fns[], void const* args[], size_t count) {
  50. for (size_t i = 0; i != count; ++i)
  51. {
  52. pack_fns[i](args[i]);
  53. }
  54. }
  55.  
  56. int main() {
  57. somestruct ss;
  58. ss.pack(foo{}, 1, 3.14);
  59. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
foo 1 3.14