c++ - 使用流模板以避免复制代码会产生 "error C4430: missing type specifier - int assumed"

标签 c++ templates

我正在尝试编写一个模板,用于从文件读取/向文件写入结构。

为了避免愚蠢的错误,我想保留一份读/写逻辑拷贝 - 而不是在两个单独的读/写函数中保留两份拷贝。

但截至目前,我收到了error C4430: missing type specifier - int assumed,

我在以下地方发表了评论:

struct VehicleInfo
{
    int Model;
    int WindowTint;
    int Kit;
};

template <typename T> stream_perform(std::ofstream& stream, T& what)
{
    stream.write(reinterpret_cast<char*>(&what), sizeof(T));
}//error on this line

template <typename T> stream_perform(std::ifstream& stream, T& what)
{
    stream.read(reinterpret_cast<char*>(&what), sizeof(T));
}//error on this line

template <typename T> T& stream_op(T& stream, VehicleInfo& info)
{
    stream_perform(stream, info.Model);//T int
    stream_perform(stream, info.WindowTint);//T int
    stream_perform(stream, info.Kit);//T int
    //hundreds lines more of variables
    return stream;
}

std::ofstream& operator<<(std::ofstream& stream, VehicleInfo& info)
{   
    return stream_op(stream, info);
}

std::ifstream& operator>>(std::ifstream& stream, VehicleInfo& info)
{
    return stream_op(stream, info);
}

我想知道,编译器可以推导出所有类型,为什么它不能编译这个,它是否认为没有指定类型?

最佳答案

I'm wondering, the compiler can deduce all types so why can't it compile this and does it think that there is no type specified?

没有指定类型:

template <typename T>      stream_perform(std::ofstream& stream, T& what)
                      ^^^^

你需要里面的东西。我猜你打算写:

template <typename T> void stream_perform(std::ofstream& stream, T& what)

关于c++ - 使用流模板以避免复制代码会产生 "error C4430: missing type specifier - int assumed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31601556/

相关文章:

c++ - 如何检查功能模板是否已专门化?

django - 在 django 中动态选择要扩展的基本模板

c++ - 从继承类 C++ 获取模板类型

c++ - 如何设计我的类(class)以利用工厂并可扩展?

c++ - undefined reference ,但已定义

c++ - 如何存储模板类型以供以后分配使用?

c++ - 如何在 for 循环中声明第二个迭代器?

C++模板类运算符重载

c++ - 在类里面使用模板

c++ - 为什么向下转型需要类型转型才能发挥作用?