Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

There is a well-known trick to cause a compile-time error in the evaluation of a constexpr function by doing something like this:

constexpr int f(int x) {
    return (x != 0) ? x : throw std::logic_error("Oh no!");
}

And if the function is used in a constexpr context you will get a compile-time error if x == 0. If the argument to f is not constexpr, however, then it will throw an exception at run time if x == 0, which may not always be desired for performance reasons.

Similar to the theory of assert being guarded by NDEBUG, is there a way to cause a compile-time error with a constexpr function, but not do anything at run time?

Finally, do relaxed constexpr rules in C++1y (C++14) change anything?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
659 views
Welcome To Ask or Share your Answers For Others

1 Answer

Is there a way to cause a compile-time error with a constexpr function, but not do anything at run time?

You can use the exact same trick, but instead of using a throw-expression, use an expression that is not a constant expression but does what you want at runtime. For instance:

int runtime_fallback(int x) { return x; } // note, not constexpr
constexpr int f(int x) {
  return (x != 0) ? x : runtime_fallback(0);
}

constexpr int k1 = f(1); // ok
constexpr int k2 = f(0); // error, can't call 'runtime_fallback' in constant expression
int k3 = f(0);           // ok

Do relaxed constexpr rules in C++1y (C++14) change anything?

Not in this area, no. There are some forms of expression that are valid in constant expressions in C++14 but not in C++11, but neither throw-expressions nor calls to non-constexpr functions are on that list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...