2012-09-08 3 views
1

다음 스 니펫에서 간단히 노출되는 사용자 정의 ostream 클래스를 생성합니다. std::endl을 사용할 수 있기를 원하지만 컴파일러가 나를 허용하지 않습니다. 나는 왜 그런지 이해하지 못한다.사용자 정의 std :: ostream 클래스에서 std :: endl을 사용하는 방법

main.cpp:21:21: error: no match for ‘operator<<’ in ‘operator<< ((* & f), (*"aa")) << std::endl’ main.cpp:21:21: note: candidates are: main.cpp:13:9: note: template Foo& operator<<(Foo&, U&&) main.cpp:13:9: note: template argument deduction/substitution failed: main.cpp:21:21: note:
couldn't deduce template parameter ‘U’

이 왜 매개 변수를 U를 추론 할 수 없습니다

#include <iostream> 

struct Bar 
{ 
}; 

template <typename T> 
struct Foo 
{ 
}; 

template <typename T, typename U> 
Foo<T>& operator<<(Foo<T>& _foo, U&&) 
{ 
    return _foo; 
} 

int main() 
{ 
    Foo<Bar> f; 
    f << "aa" << std::endl; 
} 

오류 GCC 4.7.1 날입니다 준다? 이것은 typeof(std::endl)이 아니어야합니까? std::endl 이후

+0

'typeof' 란 무엇입니까? – oldrinb

+1

우리는'decltype'과'typeid'를 가지고 있습니다. – chris

+0

@oldrinb java의 일부 연산자입니다. 나는'decltype '을 의미했다. – qdii

답변

4

당신의 클래스가 basic_ostream에서 파생되지

namespace std { 
template <class charT, class traits> 
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os); 
} 

, 그래서 그것은 작동하지 않습니다.

그리고 basic_ostreamstd::endl 같은 조종 작품

basic_ostream<charT,traits>& operator<< 
(basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&)) 

있습니다.

+0

그래,'basic_ostream'에서 정말로 파생시킬 수 있습니까? 나는 그 소멸자가 가상이 아니라고 생각했다. – qdii

+0

@qdii 왜 자신 만의 스트림 클래스가 필요한가요? 예를 들어'std :: basic_ostringstream'은'std :: basic_ostream'에서 파생됩니다. 'std :: basic_ostream'에는 가상의 가상 서버가 있습니다. – ForEveR

2

템플릿 접근법을 사용하거나 std::ostream 사용자 지정 std::streambuf을 편리하게 초기화하는 것 이외의 목적으로는 std::ostream에서 파생시키는 것이 거의 필요하지 않습니다. 읽고 쓸 소스 또는 대상을 새로 만들려면 std::streambuf에서 파생됩니다. 쓰기 스트림의 경우 일반적으로 std:;streambuf::overflow()std::streambuf::sync()을 덮어 씁니다.

관련 문제