-
Notifications
You must be signed in to change notification settings - Fork 1
Flexical scoping
Sidney San Martín edited this page Nov 21, 2013
·
1 revision
#include <iostream>
using namespace std;
// Assume that we've got some globally-available logging, stats, and profiling
// things. We might use them from lots of places, like libraries that don't
// know if they're being used by a web server, an RPC server, or a one-off
// script. Our web server wants to tie log messages that result from a request
// to information about the request (the path, the user ID, etc.). How do?
//
// One option would be to pass around a state object, but this just sucks.
// Everything that might ever log anything would need it.
//
// So, what if Team had a kind of box that could be assigned to, whose value
// would be visible from that context and any contexts which inherited from it?
// Different values could be simultaneously visible from different contexts.
//
// +--------+
// | main() |
// +--------+
// /-----------|-----------\
// +---------+ +---------+ +---------+
// | request | | request | | request |
// +---------+ +---------+ +---------+
// | | |
// assign assign assign
// logging info logging info logging info
// | | |
// ... ... ...
// | | |
// +-------+ +-------+ +-------+
// | log() | | log() | | log() |
// +-------+ +-------+ +-------+
class {
string prefix() {
return "";
}
public:
void warn(const char *message) {
cout << prefix() << message << endl;
}
} log;
namespace worklib {
void doWork() {
log.warn("Working on user...");
}
}
int main() {
HTTP::Server([](auto req, auto res) {
log.setPrefix(req.path);
doWork();
});
}