Search code examples
c++constexprc++17if-constexpr

Equivalent ternary operator for constexpr if?


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

Solution

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

    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.