2012-11-29 15 views
1

가변 템플릿 C++ 11의 기능을 사용하여 함수의 모든 인수를 인쇄하고 싶습니다.암시 적 변환 연산자

struct concatenate 
{ 

    template< typename ...ARGS > 
    explicit 
    concatenate(ARGS const & ...args) 
    { 
     cat(args...); 
    } 

    /*explicit*/ 
    operator std::string const() const 
    { 
     return oss.str(); 
    } 

private : 

    std::ostringstream oss; 

    void cat() const 
    { ; } 

    template< typename T, typename ...ARGS > 
    void cat(T const & head, ARGS const & ...tail) 
    { 
     if (oss.tellp() > 0) { 
      oss << ' '; 
     } 
     oss << head; 
     cat(tail...); 
    } 

}; 

그럼 난 그것을 테스트 해보십시오 : 그리고 다음했다

std::cout << '\'' << concatenate(1, 2, 3, 4, std::string("ololo"), "alala", 'o', 1.2, 1.2L, 1.2f) << '\'' << std::endl;

하지만 오류가 컴파일되지 않는 코드 제공 :

error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&' c:\mingw\lib\gcc\mingw32\4.7.0\include\c++\ostream:600: error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = concatenate]'

무엇 오류의 본질은 무엇입니까? 결국, 컴파일러는 변환 연산자를 사용할 수 밖에 없습니다. 그렇지 않아?

+1

변환 연산자는 명시 적이지만 명시 적 변환을하지 않았습니다. –

+0

아무런 차이가 없습니다. 'explicit' 키워드가 없으면 모두 같습니다. – Orient

답변

3

연산자 표준 : basic_string가 (유리) 함수 템플릿로 정의 클래스 템플릿 < <. 템플릿이 아닌 함수와는 달리, 템플릿 인수 공제에는 가능한 인수 변환이 포함되지 않습니다. 템플리트 된 연산자 < < for basic_string은 올바른 인수로 정확하게 문자열을 필요로하며 암시 적 변환 (병합에서 문자열로)이 작동하지 않습니다.

1

당신은 명시 적 변환 연산자를 사용하지 않을 때문에 당신은 그것을 호출하려고 클래스에 대한 operator<< 오버로드되지 않은 :

template <class charT, class traits, class T> 
basic_ostream<charT, traits>& 
operator<<(basic_ostream<charT, traits>&& os, const T& x); 

std::string(concatenate(1, 2, 3, 4, std::string("ololo"), "alala", 'o', 1.2, 1.2L, 1.2f)) 

옳은 일을 수행하는 명시 적 변환을 사용하여 .