User defined literal arguments are not constexpr?

后端 未结 5 1095
余生分开走
余生分开走 2021-01-01 11:43

I\'m testing out user defined literals. I want to make _fac return the factorial of the number.

Having it call a constexpr function works,

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 12:37

    I don't know if there's a better way in C++11 to do this than the current accepted answer, but with relaxed constexpr in C++14, you can just write "normal" code:

    constexpr unsigned long long int operator "" _fac(unsigned long long int x) {
        unsigned long long int result = 1;
        for (; x >= 2; --x) {
            result *= x;
        }
        return result;
    }
    
    static_assert(5_fac == 120, "!");
    

提交回复
热议问题