2013-08-15 10 views
1

나는 많은 로깅 기능을 가지고 있는데, 지금은 ostringstream&을 수용합니다. 난 여전히 일을해야 레거시 코드를 많이 가지고 있기 때문에ostream에서 인쇄하려고하지만 공백을 인쇄하려고합니다.

MyPrint(ostringstream() << "hello!" << endl); 

나는 상당히 방법 프로토 타입을 변경할 수 없습니다 : 내 목표는이 같은 한 줄에 기록 스트림, 무언가를 받아 들일 그들이 할 수 있도록하는 것입니다. 반환 값 형식이 <<이기 때문에이 값을 ostream&으로 변경하고 싶습니다. 현재 프로토 타입의 형식은 :

void MyPrint(ostream& stream) 
{ 
    stringstream ss; 
    ss << stream.rdbuf(); 
    cout << "ss is:" << ss.str() << endl; 
} 

다음 줄 작동 :

MyPrint(stringstream().flush() << "hello world!" << endl); 

void MyPrint(<some parameters>, ostringstream& stream) 

여기 c++ stringstream to ostream to string을 읽은 후 내 제안 된 변화이다 (다른 매개 변수는 무시 할 수 있습니다)

그러나 공백이 인쇄됩니다.

ostringstream oss; 
oss << "hello world!" << endl; 
MyPrint(oss); 

(실제로는 stringstream과 함께 사용했을 것입니다.)

두 번째 양식은 내 기존 코드가 작성된 방식이므로 작동해야합니다. 나는 해결책을 사랑 stringstream().flush() 같은 우아 뭔가를 작성할 필요 피할 수있는 경우에도

는 해당 스레드의 모든 솔루션은

wrapper() << "string" 

을 할 경우 작동하지만 당신이 할 경우 컴파일되지 않습니다

wrapper() << "string" << endl 

편집 : 내가 망가지서는 안되는 오래된 프로토 타입에 대해 명확히했습니다.

답변

1

반환 유형 < <은 원하는 유형이 될 수 있습니다. 자신 만의 유형을 만드십시오. 유일한 제한은 ostringstream 코드가 작동해야한다는 것입니다. endl 및 기타 조작자에 대한 지원은 간단합니다. 이 체크 아웃 :

#include <iostream> 
#include <sstream> 
#include <iomanip> 

struct MyStream 
{ 
    mutable std::ostringstream ss; 

    MyStream() {} 
    MyStream(std::ostringstream & oss) { ss << oss.str(); } 
}; 

typedef std::ostream & (*manipulator_t) (std::ostream &); 

const MyStream & operator << (const MyStream & s, manipulator_t m) 
{ 
    s.ss << m; 
    return s; 
} 

template <class T> 
const MyStream & operator << (const MyStream & s, T v) 
{ 
    s.ss << v; 
    return s; 
} 

void MyPrint(const MyStream & s) 
{ 
    std::cout << "logged: " << s.ss.str(); 
} 

int main() 
{ 
    MyPrint(MyStream() << "true && false == " << std::boolalpha << (true && false) << std::endl); 

    std::ostringstream oss; 
    oss << std::setw(22) << "Hello, World!" << std::endl; 
    MyPrint(oss); 
} 

온라인 데모 - 당신은 많은 응답을하지 않았다으로>http://ideone.com/Gm7Cnc

+0

<< 연산자를 멤버 함수가 아닌 특별한 이유가 있습니까? –

+0

아니요,이 연산자 (<<, >>) 비 멤버 함수를 만드는 것은 습관적 인 습관 일뿐입니다. 당신은 그것을 멤버 함수로 만들 수 있으며, 이것은 당신이 변경 가능하고 몇몇 const 한정자들을 제거 할 수있게 해줄 것입니다. – d0c

1

, 나는 약간의 변화와 같은 질문을 기록했다. 다행히도, 나는 정답을 얻었다. 보시려면 HERE을 입력하십시오.

기본적으로 std::ostringstream의 은 전달되는 플래그가 다르기 때문에 어떤 출력도 나오지 않으므로 읽기를 지원하지 않습니다.