Skip to content

Instantly share code, notes, and snippets.

@wancw
Last active August 29, 2015 14:08
Show Gist options
  • Save wancw/f8862354a3d4d9b8c7fd to your computer and use it in GitHub Desktop.
Save wancw/f8862354a3d4d9b8c7fd to your computer and use it in GitHub Desktop.
C++ implementation of accumulator described in http://www.paulgraham.com/icad.html
template<typename T>
struct Accumulator {
Accumulator(T n) : n_{n} {}
template <typename U>
const T& operator()(const U& i) { return n_ += i; }
private:
T n_;
};
template <typename T>
Accumulator<T> accumulator(const T& n) {
return Accumulator<T>(n);
}
#include <iostream>
int main(int argc, char* argv[]) {
auto acc = Accumulator<int>(10);
std::cout << acc(2) << ", ";
std::cout << acc(3.6) << std::endl;
std::cout << accumulator(10.2)(1) << std::endl;
std::cout << accumulator(std::string{"hello"})(std::string{", world"}) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment