Fel*_*bek 4 c++ conditional-operator
我有这个代码:
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
Run Code Online (Sandbox Code Playgroud)
有没有办法避免代码重复,仍然有简洁的代码?
你可以定义一个小函数:
whatever_t strOrNull(whatever_t str) {
return str ? str : L"null";
}
Run Code Online (Sandbox Code Playgroud)
然后你的代码变成了
std::wstringstream outstream;
outstream << strOrNull(prop.m_pwszOriginalVolumeName) << L";"
<< strOrNull(prop.m_pwszSnapshotDeviceObject) << L";"
<< strOrNull(prop.m_pwszOriginatingMachine) << L";"
<< ... // some more strings here
Run Code Online (Sandbox Code Playgroud)
或者如果你想更简洁,你可以这样做(取决于是什么whatever_t;如果wstringstream已经有operator<<该类型的重载,这将不起作用):
wstringstream& operator<<(wstringstream& out, whatever_t str) {
if (str)
out << str;
else
out << L"null";
return out;
}
Run Code Online (Sandbox Code Playgroud)
然后你的代码变成了
std::wstringstream outstream;
outstream << prop.m_pwszOriginalVolumeName << L";"
<< prop.m_pwszSnapshotDeviceObject << L";"
<< prop.m_pwszOriginatingMachine << L";"
<< ... // some more strings here
Run Code Online (Sandbox Code Playgroud)