0

C++

これは、s を使用して書き込むことができる限り、<<an の演算子を使用した出力動作を模倣するクラスを作成する試みです。このクラスには、ポインターという 1 つのデータ メンバーがあります。このクラスには 2 つのオーバーロードされた演算子があります。1 つは を受け取り、もう 1 つは関数へのポインターを受け取ります。引数は参照であり、参照を返します。これによると、それは の署名です。技術的には、以下のプログラムは指定された入力で動作します。2 つの s で区切られた 2 行のテキストをファイルに出力できます。ただし、文字列以外のパラメーターのオーバーロードされたオペレーターが受け入れてほしいofstreamstd::endlstringofstream<<std::stringostreamostreamstd::endlstd::endl<<std::endl単にその署名に一致するものではありません。with と without 、 withstd::endlと without 、引数リストに配置するさまざまな組み合わせを試しましたが、すべての組み合わせでコンパイラエラーが発生しました。C++11 の回答も歓迎します。*&

#include <fstream>
#include <iostream>
#include <string>

class TextOut
{
public:
    TextOut(std::ofstream* ofsPar) : ofs(ofsPar) {}
    TextOut& operator<<(std::string s)
    {
        *ofs << s;
        return *this;
    }
    TextOut& operator<<(std::ostream& (*endlPar) (std::ostream& os))
    {
        *ofs << std::endl;
        return *this;
    }
private:
    std::ofstream* ofs;
};

int main()
{
    std::cout << "Enter filename: ";
    std::string filename;
    std::cin >> filename;
    std::ofstream myofstream(filename.c_str());
    TextOut myTextOut(&myofstream);
    myTextOut << "Hello," << std::endl << std::endl << "spacious world.";
    return 0;
}

出力:

Hello,

spacious world.
4

2 に答える 2

2

ostream ヘッダー ファイルを見ると、次のように表示されますendl

template<typename _CharT, typename _Traits> inline basic_ostream<_CharT, _Traits>&
  endl(basic_ostream<_CharT, _Traits>& __os)
  {
     return flush(__os.put(__os.widen('\n')));
  }

そのため、これを機能させるには継承する必要があるようですbasic_ostream。あなたが本当にそれをしたいかどうかわかりません。

于 2013-03-05T03:20:18.473 に答える
1

私の知る限り、コンパイル時にパラメーターを特定の値にする方法はありません。
コンパイル時の強制が必要でない場合は、次のような単純な assert を使用して、パラメーターが であることを強制できますstd::endl

assert(static_cast<std::ostream& (*) (std::ostream& os)>(&std::endl) == endlPar);
于 2013-03-05T03:07:07.853 に答える