Calculating and printing factorial at compile time in C++

前端 未结 4 817
逝去的感伤
逝去的感伤 2020-12-01 12:34
template
struct Factorial {
    enum { value = n * Factorial::value};
};

template<>
struct Factorial<0> {
    enum {val         


        
4条回答
  •  日久生厌
    2020-12-01 12:57

    i am learning basics of TMP, and want to know the result at compile to make sure logic is correct.

    In that case, what you really want is a static assertion:

    static_assert(Factorial<5> ::value ==     120,  "5! should be 120");
    static_assert(Factorial<10>::value == 3628800, "10! should be 3628800");
    

    If your compiler does not support static_assert yet, you can use BOOST_STATIC_ASSERT.

提交回复
热议问题