75

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;    
};
6
  • No, there isn't. But we can suggest a workaround if you tell us more about what you want to do.
    – Brian Bi
    Dec 7, 2016 at 7:54
  • 1
    Isn't it okay to assume that if a ternary expression can be constexpr, then the compiler will compute it at compile-time regardless? (In other words, no need for a special constexpr ternary operator)
    – qxz
    Dec 7, 2016 at 7:56
  • 18
    @qxz I think a true analogue to if constexpr would also have the property that the branch not taken would be discarded (so the whole thing would compile even if that branch doesn't compile).
    – Brian Bi
    Dec 7, 2016 at 7:57
  • Just added a small example
    – wimalopaan
    Dec 7, 2016 at 8:08
  • 1
    If you want conditional compilation, as @Brian mentions, but you still want the initialization logic at the initialization site, you could call a C++17 constexpr lambda containing an if constexpr expression. Dec 14, 2016 at 1:26

3 Answers 3

63

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.

1
  • 2
    They weren't kidding when they said that constexpr lambas are powerful. Today I was using a recursive template to calculate binomial coefficients at compile time. This came in handy when optimizing for when K > N/2. Nov 20, 2022 at 1:12
38

You seem to be acting under the belief that if constexpr is a performance optimization. It isn't. If you put a constant expression in a ?: clause, any compiler worth using will figure out what it resolves to and remove the condition. So the code as you have written it will almost certainly compile down to a single option, for a particular Mode.

The principle purpose of if constexpr is to eliminate the other branch entirely. If used in a template where the condition is based on a template parameter, the compiler skips most of the checks for validity of the code in that branch. This would be for something where you if constexpr(is_default_constructible_v<T>), and if it is true, you do T(). With a regular if statement, if T isn't default constructible, T() will still have to be valid code even if the surrounding if clause is a constant expression. if constexpr removes that requirement; the compiler will discard statements that are not in the other condition.

This becomes even more complicated for ?:, because the expression's type is based on the types of the two values. As such, both expressions need to be legal expressions, even if one of them is never evaluated. A constexpr form of ?: would presumably discard the alternative that is not taken at compile time. And therefore the expression's type should really only be based on one of them.

That a very different kind of thing.

5
  • 20
    I was looking for such an constexpr ?: exactly because of type disparity: I would like to move-construct a local variable declared as auto with the result of the expression, which I can't with a regular if constexpr without wrapping it in a function (or IIFE, see @Barry's answer). I would have preferred to avoid that syntactic noise.
    – burnpanck
    Mar 16, 2019 at 12:25
  • 3
    Even discarded statements must be syntactically valid, but they need not be semantically valid (and they can do quasi-syntactic things like declare variables of nested types that don’t exist). Mar 12, 2021 at 22:06
  • 3
    Compilers do alter code generation in debug (non-optimized) builds according to constexpr. So while it's not an optimization for release builds, it very much can be an optimization for debug builds to use constexpr in conditionals. This is especially useful in complex templates in which many code paths exist but only one is possible depending on template parameters. Such functions in the past have been very heavy when trying to debug a problem, but with constexpr can be lightened considerably without having to rely on clever optimization features of compilers and debug symbol info.
    – jstine
    May 8, 2021 at 21:05
  • 1
    This reads wrong, it's already mentioned but the compiler definitely checks all branches of if constexpr - they must all be able to compile. This often makes it a good alternative to #ifdef ... #else ... #endif to ensure all blocks are buildable without actually building for all.
    – Zitrax
    Jul 26, 2023 at 9:01
  • 1
    @Zitrax: "the compiler definitely checks all branches of if constexpr - they must all be able to compile" Not if the condition is based on a template parameter of the code if constexpr is found within. I updated the answer to make it more clear that it only works in specific circumstances. Jul 26, 2023 at 13:39
0

Accepted answer can also be translated into a template function for convenience:

#include <type_traits>
#include <utility>

template <bool cond_v, typename Then, typename OrElse>
decltype(auto) constexpr_if(Then&& then, OrElse&& or_else) {
    if constexpr (cond_v) {
        return std::forward<Then>(then);
    } else {
        return std::forward<OrElse>(or_else);
    }
}

// examples

struct ModeFalse { static constexpr bool write = false; };
struct ModeTrue { static constexpr bool write = true; };

struct A {};
struct B {};

template <typename Mode>
auto&& test = constexpr_if<Mode::write>(A{}, B{});

static_assert(std::is_same_v<A&&, decltype(test<ModeTrue>)>);
static_assert(std::is_same_v<B&&, decltype(test<ModeFalse>)>);

const A a;
B b;

template <typename Mode>
auto&& test2 = constexpr_if<Mode::write>(a, b);

static_assert(std::is_same_v<const A&, decltype(test2<ModeTrue>)>);
static_assert(std::is_same_v<B&, decltype(test2<ModeFalse>)>);
4
  • 1
    This of course doesn’t avoid evaluating both sides, but if the main issue is a difference in their types it could be very handy. Mar 12, 2021 at 22:04
  • 2
    Yeah, I agree. Arguments of constexpr_if must be well-formed for this to work contrary to the accepted answer.
    – ofo
    Mar 12, 2021 at 22:11
  • This will not short circuit, meaning it will always evaluate both Then and OrElse. If there are side-effects that will ruin your day.
    – Johan
    May 13, 2022 at 10:45
  • 1
    @Johan How is that different from evaluating both sides as noted by Davis above? Also side effects don't make much sense in compile-time. Do you have any examples of a constexpr expression with said side effects?
    – ofo
    May 16, 2022 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.