c++ - 如何为不同的模板专业制作一个计数器?

标签 c++ class templates static template-specialization

#include<string>
#include<iostream>
using namespace std;

template<class T>
class Student_Grades
{
    string name;
    int NoExams;
    T *grades_ptr;
    static int counter;

public:
    Student_Grades(string n, int no)
    {
        name=n;
        NoExams=no;
        grades_ptr=new T[no];
        counter++;
    }

    void Print()
    {
        cout<<"Name: "<<name<<endl;
        cout<<"NoExams: "<<NoExams<<endl;
        for(int i=0; i<NoExams; i++)
        {
            cout<<"Grade "<<i+1<<": "<<grades_ptr[i]<<endl;
        }
        cout<<endl<<endl;
    }

    void set_grade(int index, T grade)
    {
        grades_ptr[index]=grade;    
    }

    T get_grade(int index)
    {
        return grades_ptr[index];
    }

    int get_counter()
    {
        return counter;
    }

    ~Student_Grades()
    {
        delete[] grades_ptr;
        counter--;
    }
};

此代码将为每个模板特化创建一个不同的计数器。 如何使计数器成为全局计数器,这意味着每次创建对象时它都会递增?在 Main 中,我创建了 3 个 Student_Grades 对象,其中一个具有 int 特化。一种是双倍的,一种是炭化的。计数器给我 1。我如何让它给我 3?

最佳答案

您可以使用一个基类,其目的是计算实例的数量:

#include<cassert>

struct B {
    B() { cnt++; }
    virtual ~B() { cnt--; }
    static int cnt;
};

int B::cnt = 0;

template<typename T>
struct D: B {
    D(): B{} { }
};

int main() {
    D<int> d1;
    D<float> d2;
    assert(B::cnt == 2);
}

这样,它不依赖于特化的类型。

一个稍微更可配置的解决方案是这个:

#include<cassert>

struct C {
    C() { cnt++; }
    virtual ~C() { cnt--; }
    static int cnt;
};

int C::cnt = 0;

template<typename T, class Counter = C>
struct D: Counter { };

int main() {
    D<int> d1;
    D<float> d2;
    assert(C::cnt == 2);
}

如果你不想依赖继承,这一个:

#include<cassert>

struct C {
    C() { cnt++; }
    ~C() { cnt--; }
    static int cnt;
};

int C::cnt = 0;

template<typename T, class Counter = C>
struct D { const Counter c; };

int main() {
    D<int> d1;
    D<float> d2;
    assert(C::cnt == 2);
}

等等……

关于c++ - 如何为不同的模板专业制作一个计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675009/

相关文章:

java - 为什么我需要将随机修改器更改为静态?

java - 从Java中的游戏中删除对象(eclipse)

c++ - 什么是 multimap::emplace() 和 move()?

css - Aptana:在 .css 文件中显示未使用的 css 类

c++ - C/C++ 中的固定长度 float ?

c++ - 给定一个类型,如何派生出通用的更宽类型(例如用于溢出安全求和)?

c++11 可变参数模板编译失败

c++ - 替代 enable_if 以仅启用一个模板值的方法

c++ - 如何删除链表中连续的两项

c++ - 调用默认构造函数