C++ Using stringstream after << as parameter

后端 未结 5 1565
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:19

    Make your wrapper over std::stringstream. In this new class you can define whatever operator << you need:

    class SSB {
    public:
       operator std::stringstream& () { return ss; }
    
       template 
       SSB& operator << (const T& v) { ss << v; return *this; }
       template 
       SSB& operator << (const T* v) { ss << v; return *this; }
       SSB& operator << (std::ostream& (*v)(std::ostream&)) { ss << v; return *this; }
       // Be aware - I am not sure I cover all <<'s       
    private:
       std::stringstream ss;
    };
    
    void print(std::stringstream& ss)
    {
        std::cout << ss.str() << std::endl;
    }
    
    int main() {
      SSB ssb;
      print (ssb << "Hello" << " world in " << 2012 << std::endl);
      print (SSB() << "Hello" << " world in " << 2012 << std::endl);
    }
    

提交回复
热议问题