constexpr的等效三元运算符是否? [英] Equivalent ternary operator for constexpr if?
本文介绍了constexpr的等效三元运算符是否?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
也许我错过了一些东西,但是我找不到任何提示:C ++ 17中是否有一个相当于constexpr-if的constexpr三元运算符?
Maybe I missed something, but I can't find any hints: is there a constexpr ternary operator in C++17 equivalent to constexpr-if?
template<typename Mode>
class BusAddress {
public:
explicit constexpr BusAddress(Address device) :
mAddress(Mode::write ? (device.mDevice << 1) : (device.mDevice << 1) | 0x01) {}
private:
uint8_t mAddress = 0;
};
推荐答案
否,没有constexepr
条件运算符.但是您可以将整个内容包装在一个lambda中,然后立即对其进行评估( IIFE ):
No, there is no constexepr
conditional operator. But you could wrap the whole thing in a lambda and immediately evaluate it (an IIFE):
template<typename Mode>
class BusAddress {
public:
explicit constexpr BusAddress(Address device)
: mAddress([&]{
if constexpr (Mode::write) {
return device.mDevice << 1;
}
else {
return (device.mDevice << 1) | 0x01;
}
}())
{ }
private:
uint8_t mAddress = 0;
};
这可能不是有史以来最性感的代码,但是它可以完成工作.请注意,自 N4487 和 P0170 .
It may not be the sexiest code ever, but it gets the job done. Note that lambdas are constexpr
by default where possible as of N4487 and P0170.
这篇关于constexpr的等效三元运算符是否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文