c++ - 使用带有 int 作为字符类型的 iostreams 可以吗?

标签 c++ iostream

当试图找到 this question 的答案时,我写了这个小测试程序:

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>

void writeFile() {
    int data[] = {0,1,2,3,4,5,6,7,8,9,1000};

    std::basic_ofstream<int> file("test.data", std::ios::binary);
    std::copy(data, data+11, std::ostreambuf_iterator<int>(file));
}

void readFile() {
    std::basic_ifstream<int> file("test.data", std::ios::binary);
    std::vector<int> data(std::istreambuf_iterator<int>(file),
        (std::istreambuf_iterator<int>()));

    std::copy(data.begin(), data.end(), 
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
}


int main()
{
    writeFile();
    readFile();

    return 0;
}

它按预期工作,将数据写入文件,并在读取文件后正确打印:

0 1 2 3 4 5 6 7 8 9 1000

但是,我不确定是否存在任何陷阱(撇开字节序问题不谈,处理二进制数据时总是会遇到这些问题)?这是允许的吗?

最佳答案

It works as expected.

我不确定你在期待什么......

Is this allowed?

这可能不是可移植的。 Streams 依赖于 char_traits 和在标准中仅为 charwchar_t 定义的方面。实现可以提供更多,但我敢打赌,您依赖于这些模板的最小默认实现,而不是有意识地实现 int。如果更深入地使用会导致问题,我不会感到惊讶。

关于c++ - 使用带有 int 作为字符类型的 iostreams 可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5497284/

相关文章:

c++ - C++:可以在 bool 函数中将0或1的值返回为false和true吗?

C++ 限制泛型中的类型(和指针问题)

c++ - 从 std::cout 或 std::ofstream(file) 获取 std::ostream

c++ - 运算符和返回类型是什么意思?

c++ - boost::iostreams::counter 似乎不起作用

c++ - 类型 "int"的参数与类型 "int *"的参数不兼容

c++ - Scala 和 C++ traits 之间的关系是什么

c++ - C++ 中的子进程命令

C++/函数中的引用

c++ - 使用相同的 fstream 读取和写入相同的文件