2017-01-26 11 views
-2

この擬似コードはどうすれば動作させることができますか?出力ストリームを「パラメータ化する」方法

std::ostream ostr; 
std::ofstream ofstr; 

if(condition) { 
    ostr = std::cout; 
} 
else { 
    ofstr.open("file.txt"); 
    ostr = ofstr; 
} 

ostr << "Hello" << std::endl; 

std::ostreamにはパブリックデフォルトコンストラクタがないため、これはコンパイルされません。あなたのケースでは

+0

リンク質問が_exact_の重複はありませんが、それは十分に近いですし、受け入れられた答えはあなたの問題の解決策を示します。 – Useless

+1

あなたの場合、三元演算子を使うことができます: 'std :: ostream&ostr =(condition?std :: cout:(ofstr.open(" file.txt ")、ofstr));' – Jarod42

+0

@ Jarod42: 'condition'がtrueのときに動作し、出力をcoutに出力しますが、' condition'がfalseのときにはファイルが書き込まれません。 – Pietro

答えて

1

あなたは三項演算子を使用することがあります。

std::ostream& ostr = (condition ? 
         std::cout : 
         (ofstr.open("file.txt"), ofstr)); // Comma operator also used 
                 // To allow fstream initialization. 
0
この実装は、他のストリームに切り替えることができ

:、

std::ofstream ofstr; 
std::ostream *ostr; 

ofstr.open("file.txt"); 

ostr = &ofstr; 
*ostr << "test --> file\n" << std::endl; 

ostr = &std::cout; 
*ostr << "test --> stdout\n" << std::endl; 
関連する問題