Equivalent ternary operator for constexpr if?

前端 未结 2 1273
不知归路
不知归路 2020-12-29 18:06

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

        
2条回答
  •  死守一世寂寞
    2020-12-29 18:58

    No, there is no constexepr conditional operator. But you could wrap the whole thing in a lambda and immediately evaluate it (an IIFE):

    template
    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;    
    };
    

    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.

提交回复
热议问题