Templates already provide that useful polymorphism;
template<typename T>
T callWithState(auto f) {
auto old = globalState;
globalState = whatever();
T out = f();
globalState = old;
return out;
}
(forgive any syntax errors, my C++ is very rusty...)