C++ Using stringstream after << as parameter

后端 未结 5 1537
Happy的楠姐
Happy的楠姐 2021-01-02 19:20

Is it possible to write a method that takes a stringstream and have it look something like this,

void method(string st         


        
5条回答
  •  有刺的猬
    2021-01-02 20:20

    For ease of writing objects that can be inserted into a stream, all these classes overload operator<< on ostream&. (Operator overloading can be used by subclasses, if no closer match exists.) These operator<< overloads all return ostream&.

    What you can do is make the function take an ostream& and dynamic_cast<> it to stringstream&. If the wrong type is passed in, bad_cast is thrown.

    void printStringStream(ostream& os) {
        stringstream &ss = dynamic_cast(os);
        cout << ss.str();
    }
    

    Note: static_cast<> can be used, it will be faster, but not so bug proof in the case you passed something that is not a stringstream.

提交回复
热议问题