4

听起来很简单,但我想不出一个合适的解决方案:对于寄存器分配器,我需要一个从 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;
};
4

2 回答 2

3

您可以使用 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如果未在对多态对象的引用上调用,则在编译时推导出。

于 2012-12-10T16:35:15.683 回答
1

这对我有用:

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

它取决于类型和对象。不是很优雅...

于 2012-12-10T16:37:47.570 回答