【问题标题】:Generic function for two different streams两个不同流的通用函数
【发布时间】:2017-10-23 01:57:23
【问题描述】:

我有一个函数read(),它使用ifstream 从图像中读取数据。我还为与read() 具有完全相同定义的图像重载了I/O 运算符>>,除了operator >>istream 上工作。

void read (string filename);
std::istream & operator >> (std::istream & is, Image & img); //overload >> operator
//same definition for both

有什么方法可以实现一个通用函数,可以同时用于read()operator>> 重载?

【问题讨论】:

  • 你需要一个对ifstream 的常量引用来延长它的生命周期,它也需要作为最后一个参数,因为它将是默认参数。因此,operator>> 将不起作用。所以,不,没办法。此外,这些功能不做同样的事情。 read() 不会在任何地方返回图像。
  • @Incomputable 你是在暗示可以在const istream 上执行读取操作,这怎么可能。
  • @PasserBy,我也忘了提这个问题。但是,嘿,我们有很好的老 const_cast<>() 并希望它不会炸毁世界。
  • @Incomputable 不,你不会,重载左值和右值引用
  • @PasserBy,编译器能消除歧义吗?

标签: c++ generics stream inputstream


【解决方案1】:

由于std::ifstreamstd::istream,您的读取函数可能只是调用operator >>,类似于:

std::istream & operator >> (std::istream& is, Image& img);

void read (string filename, Image& img)
{
    std::ifstream is(filename);

    if (is.is_open()) {
        is >> img;
    }
}

【讨论】:

  • 谢谢,这是有道理的。但我不知道在读取函数中作为img 传递什么。这是因为filename 实际上是图像文件,在读取时,我没有创建Image 对象。我只是将文件的内容读入我的二维数组进行操作。除非我的想法不对?
  • 如果不了解Image 和/或operator >>,很难提供更多帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-16
  • 2014-03-31
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
相关资源
最近更新 更多