c++ - 每个类型的多实例计数器

标签 c++ templates

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

相关文章:

c++ - 将 COM 对象返回给 JScript

java - 导致在文件移动到特定文件时打开批处理文件

c++ - 如何保证在运行时解密的文件被清理干净?

c++ - 如何解决 requires 子句不兼容

c++ - 转发模板参数

c++ - 模板类型的命名约定?

c++ - 具有 void 返回类型和模板化参数的 std::function

c++ - 从结构到 LPVOID 的类型转换

c++ - 输入验证无限循环C++

c++ - 理解通用引用的类型推导