【问题标题】:Why do I need to wrap iterator arguments with parenthesis? [duplicate]为什么我需要用括号包裹迭代器参数? [复制]
【发布时间】:2021-03-15 19:20:19
【问题描述】:

这是一个简单的代码 sn-p 从文件中打印出字节。

void printBytes(string path) {
  ifstream input(path, std::ios::in | std::ios::binary);

  vector<uint8_t> bytes((istreambuf_iterator<char>(input)), (istreambuf_iterator<char>()));

  input.close();

  for (uint8_t b: bytes) {
    cout << hex << setw(2) << setfill('0') << static_cast<int>(b) << endl;
  }
}

为什么传递给向量构造函数的参数需要用括号括起来?当我不包括括号时,我得到一个编译错误。但是,它们对我来说似乎是多余的,我不明白为什么需要它们。

我认为函数参数之间存在隐式分离,这样应该可以工作。

vector<uint8_t> bytes(istreambuf_iterator<char>(input), istreambuf_iterator<char>());

【问题讨论】:

  • 您认为还有什么是正确的,为什么? “编译错误”到底告诉你什么?
  • 我的印象是每个参数都有隐含的分离。像 vector&lt;uint8_t&gt; bytes(istreambuf_iterator&lt;char&gt;(input), istreambuf_iterator&lt;char&gt;()); 这样的东西我认为应该可以工作。
  • @JacobSchneider,我不确定你所说的隐式分离是什么意思,但这与一个参数完全相同,只是声明一个具有多个参数的函数。

标签: c++


【解决方案1】:

给你。没有括号,它实际上是一个函数声明。 https://en.wikipedia.org/wiki/Most_vexing_parse

【讨论】:

    猜你喜欢
    • 2012-07-29
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2016-10-06
    • 2017-11-07
    • 2015-11-01
    • 2017-09-08
    • 1970-01-01
    相关资源
    最近更新 更多