有没有更短的写法 `StringPtr ? StringPtr:“空”`?
我有这样的代码:
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
有没有一种方法可以避免代码重复并且仍然拥有简洁的代码?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你可以定义一个小函数:
然后你的代码变成
或者如果你想更简洁,你可以这样做(取决于
whatever_t
是什么;如果wstringstream
已经有该类型的operator<<
重载,这不起作用):然后你的代码变成
You could define a small function:
Then your code becomes
Or if you wanted to be even more concise, you could do this (depending on what
whatever_t
is; ifwstringstream
already has anoperator<<
overload for that type, this won't work):Then your code becomes
函数或 lambda:
A function, or a lambda:
其他的例子确实很好。还有另一种选择,但我不会推荐它(只是为了完整性而提及)。
GCC 有一个名为“带有省略操作数的条件”的扩展,它基本上看起来像这样:
与(在像您这样的简单情况下,请参阅下面的详细信息)相同:
只是不太可移植。所以你可以写:
但就像我说的,我不会推荐这个,我会使用像其他答案提到的辅助函数。
实际上,在某些情况下,它的执行方式与常规三元 if 不同,即 if 计算
a
具有副作用。从页面:请参阅http://gcc.gnu.org/onlinedocs/gcc/Conditionals.html
The other examples are really good. There is another option, though I wouldn't recommend it (only mentioning for completeness).
GCC has an extension called "Conditionals with Omitted Operands" Which basically looks like this:
which is the same as (in simple cases like yours, see below for more info):
Just less portable. So you could write:
But like I said, I would not recommend this, I would use a helper function like the other answers mention.
There actually is a case where it performs differently than a regular ternary if, and that's if evaluating
a
has side effects. From the page:See http://gcc.gnu.org/onlinedocs/gcc/Conditionals.html
一个简单的函数就可以解决问题。
A simple function should do the trick.
您可以使用辅助函数:
You could use a helper function: