Pregunta

I have this function which should take an optional stream argument to print as an errortext.

void showUsage(std::wstringstream oErrortext, bool bExit, int nExitCode)
{
    if(oErrortext.rdbuf()->in_avail() > 0)
        std::wcerr << oErrortext << std::endl;

    std::wcout << gUsage << std::endl;

    if(bExit == true)
        exit(nExitCode);
}

Now when I try to call this with a single argument, it works fine:

showUsage(std::wstringstream(L"Multiple filenames for target found"), true, 10);

But the reason why I wanted to use stringstream is, to be able to construct a generaetd string, not just static strings.

Example:

showUsage(std::wstringstream(L"Number format for offset missing -") << oParam->mOption, true, 10);

But I get a compilation error with this.

  1. How can I create this temporary object and stream the parameters with a single line (or do I have to create it first anyway so it wouldn't be possible with a single line)?
  2. Is there a better solution to what I'm trying to do here (not messing with varargs)?
¿Fue útil?

Solución

You can use a string instead of a stream:

void showUsage(std::wstring oErrortext, bool bExit, int nExitCode)
{
    if (!oErrortext.empty())
        std::wcerr << oErrortext << std::endl;
    ...
}

To use it, concatenate strings with +:

showUsage(std::wstring(L"Number format missing -") + oParam->mOption, true, 10);

My system has an incompatible return type for operator<< of stringstream (it returns a reference to ostream, not a reference to stringstream), so it's impossible to append stuff to a stringstream and send it to a function in a single line of code (it might be possible to use a static_cast, but you certainly don't want this ugly hack). So, unless this is an implementation bug (unlikely!), you must do large changes your code, like suggested above.

Otros consejos

I propose you to use a reference for the stringstream:

std::wstringstream& showUsage(std::wstringstream& oErrortext, bool bExit, int nExitCode)

(note the &)

Copying streams seems to be an issue. (Thinking of what happens with source and destination...)

If you pass it like you did, a copy of the string is needed. You can avoid this by call by reference.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top