Advertisement
devincpp

container_as_template_args

Dec 23rd, 2024
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <array>
  5. #include <set>
  6. #include <type_traits>
  7.  
  8. template <typename Container, typename = typename std::enable_if_t<std::is_same_v<typename Container::value_type, int>>>
  9. std::string toString(const Container &c, char delimiter = ' ')
  10. {
  11.     std::string res;
  12.     for (auto ele : c)
  13.     {
  14.         res += std::to_string(ele) + " " + delimiter;
  15.     }
  16.  
  17.     if (!res.empty())
  18.     {
  19.         res.pop_back();
  20.     }
  21.     return res;
  22. }
  23.  
  24. int main()
  25. {
  26.     std::vector<int> vec{1, 2, 3};
  27.     std::array<int, 3> arr{1, 2, 3};
  28.     std::set<int> set{1, 2, 3};
  29.  
  30.     std::cout << toString(vec) << std::endl;
  31.     std::cout << toString(arr) << std::endl;
  32.     std::cout << toString(set) << std::endl;
  33.     return 0;
  34. }
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement