模板类的驱动器

Destructor for template class

本文关键字:驱动器      更新时间:2023-10-16

我有模板类。其中一个参数是char*std::string。因此,我必须删除char*,然后Don t delete STD :: String``。我不知道该怎么办。

template <typename T>
class Discipline
{
public:
    unsigned int getLectureHours() const { return lecture_hours; }
    unsigned int getTotalHours() const { return total_hours; }
    unsigned int getPracticalHours() const { return practical_hours; }
    unsigned int getSelfHours() const { return self_hours; }
    T getName() const { return name; }
    Date& getDate() const { return date; }
    Discipline() : date(1,1,2000), name("Math"), total_hours(10), lecture_hours(4), practical_hours(4), self_hours(2) {}
    Discipline(Date* tdate, T& tname, int& t1, int& t2, int& t3) : date(*tdate), name(tname), total_hours(t1), lecture_hours(t2), practical_hours(t3), self_hours(t1-t2-t3){}
    Discipline(const Discipline<T>& other)
    {
        *this = other;
        name = "def";
    }
    Discipline<char*>& operator=(const Discipline<char*>& param)
    {
        if (this != &param)
        {
            this->name = new char[strlen(param.name)+1];
            strcpy(this->name, param.name);
            this->date = param.date;
            this->total_hours = param.total_hours;
            this->lecture_hours = param.lecture_hours;
            this->self_hours = param.self_hours;
            this->practical_hours = param.practical_hours;
        }
        return *this;
    }
    Discipline<std::string>& operator=(const Discipline<std::string>& param)
    {
        if (this != &param)
        {
            // this->name = "";
            // this->name += "def";
            this->date = param.date;
            this->total_hours = param.total_hours;
            this->lecture_hours = param.lecture_hours;
            this->self_hours = param.self_hours;
            this->practical_hours = param.practical_hours;
        }
        return *this;
    }
    ~Discipline<char*>() {  delete[] name; }
private:
    Date date;
    T name;
    unsigned int total_hours;
    unsigned int lecture_hours;
    unsigned int practical_hours;
    unsigned int self_hours;
};

有明确的专业化。在实施中,您可以像

一样
template<>
Discipline<string>::~Discipline(){}
template<>
Discipline<char*>::~Discipline(){
    delete[] name;
}

这甚至可以灵活地完成:

template<class T>
Discipline<T>::~Discipline(){}
template<>
Discipline<char*>::~Discipline(){
    delete[] name;
}

此变体将通过char*在类上删除delete,如果您打算将来添加更多专业化,则在其他情况下在灾难中无能为力。

您可能需要阅读http://en.cppreference.com/w/cpp/language/template_specialization

(只是为了回答问题。当然,Antred的评论是实际解决方案。)

一个变体是添加一个简单的静态方法,例如deetthestring,并带有两个参数过载。然后,您只需使用模板类型值调用,然后让编译器决定。

另一个变体是将char*包裹在unique_ptr []中,因此它会删除自身。您可以通过让小适配器类Safestore具有成员typedef std::string as,而Safestore具有typedef std::unique_ptr<char[]> as

,可以动态地做到这一点。