C++ 模板和继承

C++ templates and inheritances

考虑下面的两个 class。为了减少代码中的冗余,我想将两者结合起来。

class input_file: public ifstream {
    string str;
  public:
    input_file();
    ~input_file();
    input_file(string);
    void _name(string);
    void _open(string);
}; // input_file

class output_file: public ofstream {
    string str;
  public:
    output_file();
    ~output_file();
    output_file(string);
    void _name(string);
    void _open(string);
}; // output_file


void output_file::_open(string str) {
    open(str);
    if (!this->is_open() || !this->good()) {
        error("Can't open output file: " + str + "!"); // This will exit
    }
    if(DEBUG){debug("output_file::_open  \"(" + str + ")\"");}
}

我对 C++ 中的 templates 有所了解,我相信下面的函数会起作用。我可能必须在输出函数中使用 to_string

template<typename T>
class io_file { // Different inheritance
    string str;
  public
    ...
};

void output_file::_open(string str) {
    open(str);
    if (!this->is_open() || !this->good()) {
        error("Can't open " + T + " file: " + str + "!"); // This will exit
    }
    if(DEBUG){debug(T + "_file::_open  \"(" + str + ")\"");}
}

问题是关于 class 继承,我该如何用不同的继承编写 class 定义?

试试这个:

template<typename T>
class io_file : public T // where T can be either ifstream or ofstream 
{ // Different inheritance
    string str;
  public
    ...
};