LoginSignup
3
6

More than 5 years have passed since last update.

templateでフィボナッチ数とFizzBazz

Posted at

templateでフィボナッチ数とFizzBazz

※たいした内容じゃないです。

templateの基礎。
リハビリ兼ねて書いてみた。

この例だと全然恩恵に与ってないけど、
メタな人にはautoconstexprかなり便利っぽいなぁ。

c++11でコンパイルしてくだしあ。
g++ -std=c++11 hoge.cpp

template再帰は展開されると全部別の関数/クラスになるので、
値はコンパイル時に計算。

boost::mplが変態すぎて心が折れた。

フィボナッチ数

定義通り。

#include <iostream>

template<int N>
struct Fib {
    enum { val = Fib<N-1>::val + Fib<N-2>::val };
};

template<>
struct Fib<1> {
    enum { val = 1 };
};

template<>
struct Fib<2> {
    enum { val = 1 };
};

int main() {
    std::cout << Fib<20>::val << std::endl;
}

FizzBazz

なんかあんまりかっこよくないなぁ。

#include <iostream>

template<int N, bool fizz, bool bazz>
struct FzBz {
    static constexpr const char* str = "";
};

template<int N>
struct FzBz<N, true, false> {
    static constexpr const char* str = "Fizz";
};

template<int N>
struct FzBz<N, false, true> {
    static constexpr const char* str = "Bazz";
};

template<int N>
struct FzBz<N, true, true> {
    static constexpr const char* str = "FizzBazz";
};


template<int N>
void fizzbazz() {
    fizzbazz<N-1>();
    std::cout << N << "\t" << FzBz<N, N%3==0, N%5==0>::str << std::endl;
}
template<>
void fizzbazz<0>() {
    // pass
}


int main() {
    fizzbazz<200>();
}
3
6
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
3
6