简体   繁体   中英

stringstream operator selection issues

I have a class constructor like so:

DotDashLogMatcher( std::stringstream const& pattern );

I call it like so:

std::stringstream s;
DotDashLogMatcher( s << "test" );

This is an over-simplified example, but that is essentially what is going on. Here is the exact compiler error I'm getting. Note that for some reason the resulting object that is passed in is a basic_ostream, I am not sure if this is normal. It isn't able to cast it to an std::stringstream like my function expects.

error C2664: 'DotDashLogMatcher::DotDashLogMatcher(const stlpd_std::stringstream &)' : cannot convert parameter 1 from 'stlpd_std::basic_ostream<_CharT,_Traits>' to 'const stlpd_std::stringstream &'
        with
        [
            _CharT=char,
            _Traits=stlpd_std::char_traits<char>
        ]
        Reason: cannot convert from 'stlpd_std::basic_ostream<_CharT,_Traits>' to 'const stlpd_std::stringstream'
        with
        [
            _CharT=char,
            _Traits=stlpd_std::char_traits<char>
        ]
        No constructor could take the source type, or constructor overload resolution was ambiguous

I'm using VS2003 and STLport on Windows.

Anyone know where I'm going wrong here? Why won't this code compile? I apologize in advance if I am lacking information. I will update my question for those that request more info.

operator<< does not return a std::stringstream because it is inherited from std::ostream. See:

http://www.cplusplus.com/reference/iostream/stringstream/

You may use:

DotDashLogMatcher( s );

Or you may change your method declaration in order to match the return type.

I believe you should split the statement into two separate commands:

s << "test";
DotDashLogMatcher( s );

as the parameter is passed by reference and thus needs to be modifiable, therefore an l-value.

Maybe you want to change:

DotDashLogMatcher( std::stringstream const& pattern );

Into:

DotDashLogMatcher( std::ostream const& pattern );

The problem is that operator << is overloaded for std::ostream and returns a std::ostream .

If you can;t change it there are several workarounds.

std::stringstream s;
s << "test"
DotDashLogMatcher( s );

// slightly more dangerious but should work.
std::stringstream s;
DotDashLogMatcher( static_cast<std::stringstream const&>(s << "test") );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM