Guest User

Ctor delegation with tag dispatch

a guest
Jan 5th, 2017
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include <array>
  2. #include <iostream>
  3. #include <iterator>
  4. #include <string>
  5. #include <vector>
  6.  
  7.  
  8. // Tags for supported containers
  9. struct t_tag_array {};
  10. struct t_tag_vector {};
  11.  
  12. // Tag dispatching
  13. template<class T, size_t S>
  14. struct t_container_tag {};
  15.  
  16. template<class T, size_t S>
  17. struct t_container_tag<std::vector<T>, S> {
  18.     using type = t_tag_vector;
  19. };
  20.  
  21. template<class T, size_t S>
  22. struct t_container_tag<std::array<T, S>, S> {
  23.     using type = t_tag_array;
  24. };
  25.  
  26. // Helper to fetch the size of an std::array
  27. template<typename>
  28. struct array_size;
  29.  
  30. template<typename T, size_t S>
  31. struct array_size<std::array<T, S>> {
  32.     static const auto value = S;
  33. };
  34.  
  35. template <typename C, size_t S = array_size<C>::value>
  36. struct foo
  37. {
  38.     using value_type = typename C::value_type;
  39.  
  40.     // Constructor
  41.     template<typename... Args>
  42.     foo(Args&&... args) : foo(typename t_container_tag<C, S>::type{}, std::forward<Args>(args)...) {}
  43.  
  44.     // Specialized constructor for vectors
  45.     template<typename... Args>
  46.     foo(t_tag_vector &&, Args&&... args) : m(std::forward<Args>(args)...), container(S, value_type{}) {}
  47.    
  48.     // Specialized constructor for arrays
  49.     template<typename... Args>
  50.     foo(t_tag_array &&, Args&&... args) : m(std::forward<Args>(args)...), container{} {}
  51.  
  52.     value_type m;
  53.     C container;
  54. };
  55.  
  56. int main()
  57. {
  58.     const std::string str_data = "Hello, World!";
  59.  
  60.     foo<std::vector<int>, 7> vec_foo(42);
  61.     foo<std::array<std::string, 6>> arr_foo(std::begin(str_data), std::end(str_data));
  62.    
  63.     // The size of the containers
  64.     std::cout << vec_foo.container.size() << ' '
  65.         << arr_foo.container.size() << std::endl;
  66.  
  67.     // The m members contain the assigned values
  68.     std::cout << vec_foo.m << " \'" << arr_foo.m << '\'' << std::endl;
  69.  
  70.     // The containers are zero or default initialized
  71.     std::cout << vec_foo.container.front() << " \'" <<
  72.         arr_foo.container.front() << '\'' << std::endl;
  73.    
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment