Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- template<class T>
- struct SumClass {
- T init() { throw 1; }
- T add(const T& a, const T& b) { throw 1; }
- };
- template<class T>
- T Sum(const std::vector<T>& values) {
- SumClass<T> summer = SumClass<T>();
- T res = summer.init();
- for (const T& val : values) {
- res = summer.add(res, val);
- }
- return res;
- }
- template<>
- struct SumClass<int> {
- int init() { return 0; }
- int add(const int& a, const int& b) { return a + b; }
- };
- template<>
- struct SumClass<std::string> {
- std::string init() { return ""; }
- std::string add(const std::string& a, const std::string& b) { return a + b; }
- };
- int main() {
- std::vector<std::string> strings = {"a", "b", "c"};
- std::cout << Sum(strings) << std::endl; // prints abc
- std::vector<int> ints = {1, 2, 3};
- std::cout << Sum(ints) << std::endl; // prints 6
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment