You say static
and by design in static
languages every thing about the design of object should addressed in compile time and class can't change it self in runtime. So I don't think any static
language can do such a dynamic
job, and it is good since it will decrease performance, when you access a variable, in static
languages compiler create code to access that variable at compile time but if such a variable (function-object-static) exist, then compiler should write an extra code to check some dynamic storage to see if a property with that name exist or not and this is only because you feel sad with current design of C++!? But on the other hand, if you do not want to do it without changing fields, you can simply add one extra variable to the class of a type that can used for dynamic lookup(for example std::map
) and make that variable private
so no one except you in your class can access it:
class foo {
std::map<std::string, boost::any> functionVariables;
public:
void test1() {
int visitNumber;
auto i = functionVariables.find( "test1" );
if( i == functionVariables.end() ) {
// This is first visit of the function, initialize your variable
functionVariables["test1"] = (visitNumber = 0);
} else {
// It is already initialized, use it
visitNumber = ++ *boost::any_cast<int>(&*i);
}
}
};