【问题标题】:How to make one counter for different template specializations?如何为不同的模板专业化制作一个计数器?
【发布时间】:2026-02-08 00:05:01
【问题描述】:
#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?

【问题讨论】:

  • 你根本不使用静态成员变量,而是使用全局变量。
  • 把它放在模板外面。例如。在一个共同的基类中。
  • 是的,我只是想了一下。非常基本,对不起:) 和谢谢

标签: c++ class templates static template-specialization


【解决方案1】:

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

#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);
}

等等……

【讨论】:

    最近更新 更多