C++ Template Metaprogramming Part 2 of n

Series:

  1. C++ Template Metaprogramming
  2. C++ Template Metaprogramming Part 2 of n
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
bool isPrime(int number)
{
    if(number < 3)
        throw std::invalid_argument("numbers less than 3 cannot be primes");

    //  any even number cannot be a prime
    bool result = number % 2 != 0;

    for(int divisor = 2; result && divisor < number/2; ++divisor)
    {
        result = number % divisor != 0;
    }

    return result;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
bool isPrime_rimpl(int number, int divisor)
{
    return  number == divisor ? true :
            number % divisor == 0 ? false : isPrime_rimpl(number, ++divisor);
}

bool isPrime_r(int number)
{
    if(number < 3)
        throw std::invalid_argument("numbers less than 3 cannot be primes");

    return isPrime_rimpl(number, 2);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
template<int number>
struct isPrime_c
{
private:

    template<int number1>
    struct isEven_c
    {
        static const bool value = number1 % 2 == 0;
    };

    template<int number1, int divisor>
    struct isPrime_cimpl
    {
        static const bool value = number1 % divisor == 0 ? false
        : isPrime_cimpl<number1, divisor + 1>::value;
    };

    template<int number1>
    struct isPrime_cimpl<number1, number1>
    {
        static const bool value = true;
    };

public:
    static_assert(number > 2, "numbers less than 3 cannot be primes");
    static const bool value = isEven_c<number>::value ? false
    : isPrime_cimpl<number,2>::value;

};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
template<int idx>
struct fib_c
{
    static const int value = fib_c<idx-1>::value + fib_c<idx-2>::value;
};

template<>
struct fib_c<0>
{
    static const int value = 0;
};

template<>
struct fib_c<1>
{
    static const int value = 1;
};

#include <iostream>

int main()
{
    std::cout << fib_c<0>::value << std::endl;
    std::cout << fib_c<1>::value << std::endl;
    std::cout << fib_c<2>::value << std::endl;
    std::cout << fib_c<3>::value << std::endl;
    std::cout << fib_c<4>::value << std::endl;
    std::cout << fib_c<5>::value << std::endl;

    return 0;
}