Sounds like an easy one but I can’t figure a suitable solution to this: For register allocator I need a counter that starts counting from 0 and increments on each allocation step.
Ok, lets make this a general problem (not specific to register allocation): I need a class that can have multiple instances (that’s important!) and that has a templated member function that returns an integer which’s value is counting up on each call. The interface should look like:
class Counter
{
public:
template<class T>
int plus1() {
// ?
}
private:
// what member ?
};
When one uses the counter it should function like this:
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 when relaxing the “multiple instances” requirement this can be implemented with a static int local variable . However I need multiple instances, and I think this makes the whole thing tricky.
* SOLUTION/EDIT *
I think @log0 gave the right solution. Here for completeness the full working C++11 code (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;
};
You can use type_index (c++11)
typeidis deduced at compile time if not called on reference to polymorphic object.