Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way of writing `StringPtr ? StringPtr : "null"`?

I have this code:

 std::wstringstream outstream;
 outstream << (prop.m_pwszOriginalVolumeName 
             ? prop.m_pwszOriginalVolumeName 
             : L"null") << L";"
           << (prop.m_pwszSnapshotDeviceObject 
             ? prop.m_pwszSnapshotDeviceObject 
             : L"null") << L";"
           << (prop.m_pwszOriginatingMachine 
             ? prop.m_pwszOriginatingMachine
             : L"null") << L";"
           << ... // some more strings here

Is there a way to avoid code duplication and still have concise code?

like image 708
Felix Dombek Avatar asked Dec 10 '22 06:12

Felix Dombek


1 Answers

You could define a small function:

whatever_t strOrNull(whatever_t str) {
    return str ? str : L"null";
}

Then your code becomes

std::wstringstream outstream;
outstream << strOrNull(prop.m_pwszOriginalVolumeName)   << L";"
          << strOrNull(prop.m_pwszSnapshotDeviceObject) << L";"
          << strOrNull(prop.m_pwszOriginatingMachine)   << L";"
          << ... // some more strings here

Or if you wanted to be even more concise, you could do this (depending on what whatever_t is; if wstringstream already has an operator<< overload for that type, this won't work):

wstringstream& operator<<(wstringstream& out, whatever_t str) {
    if (str)
        out << str;
    else
        out << L"null";

    return out;
}

Then your code becomes

std::wstringstream outstream;
outstream << prop.m_pwszOriginalVolumeName   << L";"
          << prop.m_pwszSnapshotDeviceObject << L";"
          << prop.m_pwszOriginatingMachine   << L";"
          << ... // some more strings here
like image 187
Seth Carnegie Avatar answered Jan 21 '23 02:01

Seth Carnegie