听起来很简单,但我想不出合适的解决方案:对于寄存器分配器,我需要一个从 0 开始计数并在每个分配步骤递增的计数器。
好吧,让我们把它变成一个普遍的问题(不特定于寄存器分配):我需要一个可以有多个实例的类(这很重要!)并且有一个模板化的成员函数返回一个整数,这个整数的值正在计算每次通话。界面应如下所示:
class Counter
{
public:
template<class T>
int plus1() {
// ?
}
private:
// what member ?
};
当一个人使用计数器时,它应该像这样工作:
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);
}
显然,放宽“多实例”要求时,可以使用 static int
局部变量来实现。但是我需要多个实例,我认为这让整个事情变得棘手。
* 解决方案/编辑 *
我认为@log0 给出了正确的解决方案。为了完整起见,这里提供了完整的 C++11 代码(至少它似乎可以工作):
class Counter
{
public:
template<class T>
int plus1() {
return counters[ std::type_index( typeid(T) ) ]++;
}
private:
std::map<std::type_index, int> counters;
};
最佳答案
您可以使用 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
如果不是在引用多态对象时调用,则在编译时推导。
关于c++ - 每个类型的多实例计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13804899/