【发布时间】:2014-07-02 09:19:52
【问题描述】:
我想为一个结构类型确定sizeof 一个特定的成员变量,我将其作为模板参数传递给一个函数。但是,我从编译器得到一个错误,说 sizeof 操作数是非法的(我在 Windows 7 上使用 VS2010)。
考虑以下程序:
#include <vector>
#include <fstream>
struct MyFloat {
float val;
MyFloat(){val=rand()/(RAND_MAX+1.f);};
};
struct MyDouble {
double val;
MyDouble(){val=rand()/(RAND_MAX+1.);};
};
template<class T>
void serializeArrayToFile(const std::string &filename, const std::vector<T> &items) {
const size_t nbytes = sizeof(T::val); // <--- Error C2070
std::ofstream os(filename.c_str(),std::ios::out+std::ios::binary);
for(size_t i=0; i<items.size(); ++i)
os.write((char*)(&items[i].val),nbytes);
os.close();
};
void main() {
const int N = 15;
std::vector<MyFloat> arr_float(N); // Filled randomly by default constructor
std::vector<MyDouble> arr_double(N); // Filled randomly by default constructor
serializeArrayToFile<MyFloat>("myfloat_array.dat",arr_float);
serializeArrayToFile<MyDouble>("mydouble_array.dat",arr_double);
}
这会产生以下错误: 错误 C2070:“”:操作数大小非法。
有人可以解释为什么sizeof(T::val) 是非法的,以及考虑到输入向量可能为空,我应该如何确定sizeof T::val?
【问题讨论】:
-
sizeof 下的表达式不求值,所以你可以放心使用
items[0].val。 -
@n.m 有趣,我不知道。知道为什么这个特定的
sizeof表达式会失败吗?