LoginSignup
12
11

More than 5 years have passed since last update.

変数テンプレート(C++14)だけで階乗を計算する

Posted at

C++14で導入された変数テンプレートは再帰的に使えます

#include <iostream>

template <std::size_t N> constexpr std::size_t fact = fact<N - 1> *N;
template <> constexpr std::size_t fact<1> = 1;

int main(int argc, char const *argv[]) {
  std::cout << fact<10> << std::endl;
  return 0;
}

つまりこれだけでコンパイル時に階乗が計算できます。

clang3.5で動いた
[Wandbox]三へ( へ՞ਊ ՞)へ ハッハッ:

12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11