typenameの罠に見事に嵌った。VCって意外と賢かったのか…
#include <iostream> #include <string> #include <sstream> #include <map> #include <boost/asio.hpp> #include <boost/timer.hpp> using namespace std; template <class I, class O> class Cache { map<I, O> m_; O (*f_)(I x); public: Cache(O (*f)(I x)): f_(f) {} O operator ()(I x) { typename map<I, O>::iterator i; i = m_.find(x); if (i != m_.end()) { return i->second; } else { O tmp = f_(x); m_.insert(pair<I, O>(x, tmp)); return tmp; } } }; namespace { string forecast(string query) { using namespace boost::asio; ip::tcp::iostream s("weather.livedoor.com", "http"); s << "GET /forecast/webservice/rest/v1?" << query << " HTTP/1.1\r\n"; s << "Host: weather.livedoor.com\r\n"; s << "\r\n"; s << flush; ostringstream out; string l; while (getline(s, l)) { out << l << endl; } return out.str(); } } int main(int argc, char* argv[]) { Cache<string, string> proxy(forecast); boost::timer t; proxy("city=113&day=tomorrow"); cout << "1: " << t.elapsed() << "s" << endl; t.restart(); proxy("city=113&day=tomorrow"); cout << "2: " << t.elapsed() << "s" << endl; t.restart(); proxy("city=113&day=tomorrow"); cout << "3: " << t.elapsed() << "s" << endl; return 0; }
Linux上だとasio速いなー。