Created
October 1, 2016 05:11
-
-
Save sighingnow/0a1652b6ae14dd60b2e3fd16282e7340 to your computer and use it in GitHub Desktop.
Notes on constexpr in C++.
This file contains hidden or 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
#include <type_traits> | |
#include <iostream> | |
#include <string> | |
// valid in C++14, but not valid in C++11. | |
// for statement not allowed in constexpr function in C++11. | |
constexpr size_t addition(size_t n) { | |
size_t s = 0; | |
for (size_t i = 0; i <= n; ++i) { | |
s += i; | |
} | |
return s; | |
} | |
// if BOUND is 0xffffc, will failed in compile time. | |
/* | |
#define BOUND 0xffffb | |
constexpr int foo(int a) { | |
int b = 1; | |
for (int k = 0; k < a; k++); | |
return b; | |
} | |
int t[foo(BOUND)]; | |
*/ | |
// In C++14, constexpr doesn't imply const. | |
struct non_negative { | |
size_t i; | |
constexpr size_t const & get() const { return i; } | |
size_t & get() { return i; } | |
}; | |
int main(int, char **) { | |
int n; | |
scanf("%d", &n); | |
addition(n); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment