Skip to content

Instantly share code, notes, and snippets.

@sighingnow
Created October 1, 2016 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sighingnow/0a1652b6ae14dd60b2e3fd16282e7340 to your computer and use it in GitHub Desktop.
Save sighingnow/0a1652b6ae14dd60b2e3fd16282e7340 to your computer and use it in GitHub Desktop.
Notes on constexpr in C++.
#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