【发布时间】: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