7

ファイルの内容を文字列に読み取るために、次のコード ( from here ) が使用されていることを理解しています。

#include <fstream>
#include <string>

  std::ifstream ifs("myfile.txt");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

しかし、なぜこのような一見冗長な括弧が必要なのか理解できません。たとえば、次のコードはコンパイルされません。

#include <fstream>
#include <string>

  std::ifstream ifs("myfile.txt");
  std::string content(std::istreambuf_iterator<char>(ifs),
                      std::istreambuf_iterator<char>()    );

これをコンパイルするには、なぜこれほど多くの括弧が必要なのですか?

4

1 に答える 1

12

かっこがないため、コンパイラはそれを関数宣言として扱い、 acontentを返し、a を返す引数を取らない関数である名前付きパラメーターと名前なしパラメーターを引数std::stringとして取る名前付き関数を宣言します。std::istreambuf_iterator<char>ifsstd::istreambuf_iterator<char>

括弧を使用するか、アレクサンドルがコメントで指摘しているように、そのようなあいまいさのない C++ の均一な初期化機能を使用できます。

std::string content { std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() };

またはロキが言及しているように:

std::string content = std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
于 2012-09-25T19:51:03.517 に答える