Multiple instance counter for each type

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() { // ? } private: // what member ? }; 

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; }; 
+4
source share
2 answers

You can use type_index (C ++ 11)

 class Counter { public: template<class T> int plus1() { return map_[std::type_index(typeid(T))]++; } private: std::map<std::type_index, int> map_; }; 

typeid is output at compile time if a reference to a polymorphic object is not called.

+3
source

This works for me:

 class Counter { public: template<class T> int plus1() { static std::map<Counter*, int> s_counters; return s_counters[this]++; } }; 

Type and object are dependent. Not very elegant ...

+1
source

All Articles