It sounds simple, but I can’t find a suitable solution for this: for the register allocator, I need a counter that starts counting from 0 and increases at each stage of the allocation.
Well, let's make this a common problem (not specific to register allocation): I need a class that can have multiple instances (which is important!) And has a template member function that returns an integer whose value is counted every call. The interface should look like this:
class Counter { public: template<class T> int plus1() {
When a counter is used, it should work as follows:
int main() { Counter a,b; assert( a.plus1<int>() == 0); assert( a.plus1<int>() == 1); assert( b.plus1<float>() == 0); assert( b.plus1<float>() == 1); assert( a.plus1<float>() == 0); }
Obviously, if the requirement of “multiple instances” is relaxed, this can be realized using the local variable static int . However, I need several instances, and I think that makes it all the more difficult.
* SOLUTION / EDIT *
I think @ log0 gave the correct solution. Here's a complete working C ++ 11 code for completeness (at least it seems to work):
class Counter { public: template<class T> int plus1() { return counters[ std::type_index( typeid(T) ) ]++; } private: std::map<std::type_index, int> counters; };
source share