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 | |
} | |
} |
This comment has been minimized.
This comment has been minimized.
Very nice, and confirming my impression that constexpr is one of the most confusing, while useful, additions to C++. |
This comment has been minimized.
This comment has been minimized.
Good job robot ;) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Great examples!