Last active
August 29, 2015 14:07
-
-
Save rmartinho/15e4f2e48f2a746ee256 to your computer and use it in GitHub Desktop.
Constexpr myths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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"?