Skip to content

Instantly share code, notes, and snippets.

@makotoshimazu
Last active November 7, 2018 04:17
Show Gist options
  • Save makotoshimazu/326b8c5ff12cf69274e1f18e702c8986 to your computer and use it in GitHub Desktop.
Save makotoshimazu/326b8c5ff12cf69274e1f18e702c8986 to your computer and use it in GitHub Desktop.
#include "foo.h"
constexpr int Foo::kValue;
#pragma once
class Foo {
public:
static constexpr int kValue = 10;
};
#include <array>
#include <iostream>
#include "foo.h"
constexpr int addOne(int x) { return x + 1; }
int main() {
// Foo::kValue is a constant value.
std::cout << "result: " << Foo::kValue << std::endl;
// That's a constant, so you can use it as a template parameter.
std::array<int, Foo::kValue> arr = {0};
for (const auto& x : arr)
std::cout << x << " ";
std::cout << std::endl;
for (auto& x : arr)
++x;
for (const auto& x : arr)
std::cout << x << " ";
std::cout << std::endl;
// You can calculate values on compilation time if all values and functions
// are declared as constexpr.
std::array<int, addOne(Foo::kValue)> arr2;
std::cout << "arr2 size: " << arr2.size() << std::endl;
// You cannot retrieve the address if Foo::kValue doesn't have the
// storage. You need to have it at somewhere (like foo.cc).
std::cout << &Foo::kValue << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment