Skip to content

Instantly share code, notes, and snippets.

@rmartinho
Last active August 29, 2015 14:07
Show Gist options
  • Save rmartinho/15e4f2e48f2a746ee256 to your computer and use it in GitHub Desktop.
Save rmartinho/15e4f2e48f2a746ee256 to your computer and use it in GitHub Desktop.
Constexpr myths
// Myth #1: constexpr is the same as const
// (note: there is a difference between C++11 and C++14 here)
// (see: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3598.html)
namespace myth1 {
struct foo {
int i;
constexpr int& get() { return i; } // not a const function
}
int f() {
foo const& x = foo { 0 };
return x.get(); // not ok; function is not const
}
}
// Myth #2: constexpr means "immutable"
namespace myth2 {
struct foo {
int i;
constexpr int& get() { return i; }
}
int f(int y) {
foo x { 0 };
x.get() += y; // even though get() is constexpr
return x.i;
}
// even less true with relaxed constexpr
constexpr int g(int y) {
foo x { 0 };
x.get() += y; // even though get() is constexpr *and* we're in a constexpr function
return x.i;
}
}
// Myth #3: constexpr means "no side-effects"
namespace myth3 {
constexpr int f(int x) {
return x < 0?
(std::cout << "it was negative!", -1) // the compiler is ok with this here
: 2*x;
}
}
// Myth #4: constexpr means "compile-time"
namespace myth4 {
constexpr int f(int x) {
return 2*x;
}
void g() {
std::cin >> x;
std::cout << f(x); // there's no way to do this at compile-time, yet the compiler is ok with it
}
}
@olafurw
Copy link

olafurw commented Oct 8, 2014

Great examples!

@abigagli
Copy link

abigagli commented Dec 7, 2014

Very nice, and confirming my impression that constexpr is one of the most confusing, while useful, additions to C++.
One can easily get to ask: "Ok, and then what does it really mean"?

@marcodiiga
Copy link

Good job robot ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment