Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Last active May 30, 2019 15:45
Show Gist options
  • Save drmalex07/4a728ae77530c14694585d176bde9382 to your computer and use it in GitHub Desktop.
Save drmalex07/4a728ae77530c14694585d176bde9382 to your computer and use it in GitHub Desktop.
A constexpr example in C++14 with custom object initialization. #c++ #constexpr
#include <iostream>
using namespace std;
constexpr int get_magic_number(int x)
{
return x + 1999;
}
template <int N>
class foo
{
public:
static constexpr const int magic_number = get_magic_number(0);
private:
int seq[N];
int val;
public:
constexpr foo(int v): seq(), val(v)
{
for (int i = 0; i < N; ++i)
seq[i] = i + 1;
}
void print() const
{
cerr << "foo(" << val << ")" << endl;
}
int at(int i) const { return seq[i]; }
static constexpr const foo<N> foo1 = foo<N>(1);
};
int main()
{
cerr << "magic-number: " << foo<1000>::magic_number << endl;
foo<1000> foo1 = foo<1000>::foo1;
foo1.print();
cerr << "foo1.at(150) = " << foo1.at(150) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment