C ++ 클래스가 사용자 정의 타조처럼 행동하도록하십시오, Sstream
-
03-07-2019 - |
문제
C ++ 클래스가 있습니다 MyObject
그리고 나는이 데이터를 Osstream에 공급할 수 있기를 원합니다 (그러나 직접 sstream과 달리 들어오는 데이터가 특별한 방법으로 형식화되도록합니다). MyObject가 제공하기 위해 연산자에게 과부하하는 방법을 알 수없는 것 같습니다.
class MyObject {
public:
ostringstream s;
FEEDME
};
int main() {
MyObject obj;
obj.FEEDME << "Hello" << 12345;
// I want obj.s == ":Hello::12345:"
}
나는 그것을 원한다.
따라서 주어진 예에서 S = ": hello :: 12345"가 최종 결과가되어야합니다. 내 질문은 무엇인가, 어떻게 <<something
, 풋 : 주위에 뭔가 주변.
이게 가능해?
해결책
이 시도:
class MyObject {
public:
template <class T>
MyObject &operator<<(const T &x) {
s << ':' << x << ':';
return *this;
}
std::string to_string() const { return s.str(); }
private:
std::ostringstream s;
};
MyObject obj;
obj << "Hello" << 12345;
std::cout << obj.to_string() << std::endl;
스트림에 밀어 넣을 수없는 것이 있지만 모든 기본 사항에 효과가 있어야합니다.
다른 팁
답을 찾을 수 있습니다 내 자신의 타조/스트림 부프를 어떻게 만들려면? 도움이 되는.
나는 약간 다른 접근 방식을 취하고 포맷터 객체를 만들 것입니다.
그런 다음 Formater Object는 스트림에 적용될 때 형식 문자의 삽입을 처리합니다.
#include <iostream>
template<typename T>
class Format
{
public:
Format(T const& d):m_data(d) {}
private:
template<typename Y>
friend std::ostream& operator<<(std::ostream& str,Format<Y> const& data);
T const& m_data;
};
template<typename T>
Format<T> make_Format(T const& data) {return Format<T>(data);}
template<typename T>
std::ostream& operator<<(std::ostream& str,Format<T> const& data)
{
str << ":" << data.m_data << ":";
}
int main()
{
std::cout << make_Format("Hello") << make_Format(123);
}
제휴하지 않습니다 StackOverflow