使用多个继承和模板访问基类的成员

时间:2016-11-03 06:50:32

标签: c++ templates multiple-inheritance

我希望能够从文件中读取前四个整数,并能够通过它们的名称检索它们: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 *'

为什么呢? 有关更优雅解决方案的任何建议吗?

1 个答案:

答案 0 :(得分:0)

&T1::val将返回成员指针(即类似N::*),而不是指向变量的指针(即int*)。< / p>

您可以添加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);
相关问题