【问题标题】:Access the members of base classes with multiple inheritance and templates使用多重继承和模板访问基类的成员
【发布时间】:2016-11-03 06:50:32
【问题描述】:

我希望能够从文件中读取前四个整数,并能够通过它们的名称检索它们:N、H、C、W。 例如:

//some_file.mat: {10,20,30,40.....}
data_format.read_header<N,C,W,H>(some_file.mat);
cout << data_format.getN(); // prints the first read integer: 10
cout << data_format.getH(); // prints the fourth read integer: 40

data_format.read_header<C,N,H,W>(some_file.mat);
cout << data_format.getN(); // prints the second read integer: 20
cout << data_format.getH(); // prints the fourth read integer: 30

以下代码尝试使用多重继承和模板来实现这一点:

struct N{ int val; };
struct C{ int val; };
struct H{ int val; };
struct W{ int val; };

struct DataFormat : N, C, H, W
{
    template<class T1, class T2, class T3, class T4>
    bool read_header(FILE* p_file)
    {
        int res = 0;
        res += fread(&T1::val, sizeof(int), 1, p_file); //doesn't compile
        res += fread(&T2::val, sizeof(int), 1, p_file); //doesn't compile
        res += fread(&T3::val, sizeof(int), 1, p_file); //doesn't compile
        res += fread(&T4::val, sizeof(int), 1, p_file); //doesn't compile
        return (res != 0);
    }
    int getN(){ return N::val; }
    int getC(){ return C::val; }
    int getH(){ return H::val; }
    int getW(){ return W::val; }
};


static void foo(){

    DataFormat data_format;
    FILE* some_file;
    data_format.read_header<N, W, H, C>(some_file);
}

我收到下一条编译器错误消息:在所有以 res+=fread... 开头的行上

错误 C2664: 'size_t fread(void *,size_t,size_t,FILE )' : 不能 将参数 1 从 'int N:: ' 转换为 'void *'

为什么? 对更优雅的解决方案有何建议?

【问题讨论】:

    标签: c++ templates multiple-inheritance


    【解决方案1】:

    您可以添加this 限定符来访问基类中的成员变量,例如:

    res += fread(&this->T1::val, sizeof(int), 1, p_file);
    res += fread(&this->T2::val, sizeof(int), 1, p_file);
    res += fread(&this->T3::val, sizeof(int), 1, p_file);
    res += fread(&this->T4::val, sizeof(int), 1, p_file);
    

    【讨论】:

      猜你喜欢
      • 2013-05-04
      • 2012-10-26
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 2011-04-06
      相关资源
      最近更新 更多