Guest User

Untitled

a guest
Oct 18th, 2017
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. template<class T>
  5. struct SumClass {
  6.   T init() { throw 1; }
  7.   T add(const T& a, const T& b) { throw 1; }
  8. };
  9.  
  10. template<class T>
  11. T Sum(const std::vector<T>& values) {
  12.   SumClass<T> summer = SumClass<T>();
  13.   T res = summer.init();
  14.   for (const T& val : values) {
  15.     res = summer.add(res, val);
  16.   }
  17.   return res;
  18. }
  19.  
  20. template<>
  21. struct SumClass<int> {
  22.   int init() { return 0; }
  23.   int add(const int& a, const int& b) { return a + b; }
  24. };
  25.  
  26. template<>
  27. struct SumClass<std::string> {
  28.   std::string init() { return ""; }
  29.   std::string add(const std::string& a, const std::string& b) { return a + b; }
  30. };
  31.  
  32. int main() {
  33.   std::vector<std::string> strings = {"a", "b", "c"};
  34.   std::cout << Sum(strings) << std::endl; // prints abc
  35.   std::vector<int> ints = {1, 2, 3};
  36.   std::cout << Sum(ints) << std::endl; // prints 6
  37.   return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment