Skip to content

Instantly share code, notes, and snippets.

@luskan
Last active October 2, 2019 17:19
Show Gist options
  • Save luskan/c1e005c7194376cbdcf9ea080d213665 to your computer and use it in GitHub Desktop.
Save luskan/c1e005c7194376cbdcf9ea080d213665 to your computer and use it in GitHub Desktop.
Simple example for a throw trick in constexpr context
In "C++Now 2017: Ben Deane & Jason Turner "constexpr ALL the things!"", Jason Turner talks about
constexpr vector which has a push back method allowing to detect range errors at compile time:
https://youtu.be/HMB9oXFobJc?t=921
If you want to see how to reproduce this trick here is the code:
#include <stdexcept>
class vec {
public:
constexpr void test(int n) const {
if (n > 10)
throw std::range_error("error");
}
};
constexpr int foo() {
vec v;
v.test(10); // OK
v.test(11); // causes compile error: expression '<throw-expression>' is not a constant expression
return 123;
}
constexpr int ik = foo();
int main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment