Forcing a constant expression to be evaluated during compile-time?

后端 未结 1 1741
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 02:19

A few days ago I asked by which criteria the compiler decides whether or not, to compute a constexpr function during compile time.

When does a constexpr function get

相关标签:
1条回答
  • 2020-12-06 02:48

    Just to not leave it buried in comments:

    #include <type_traits>
    
    #define COMPILATION_EVAL(e) (std::integral_constant<decltype(e), e>::value)
    
    constexpr int f(int i){return i;}
    
    int main()
    {
        int x = COMPILATION_EVAL(f(0));
    }
    

    EDIT1:

    One caveat with this approach, constexpr functions can accept floating-point and be assigned to constexpr floating-point variables, but you cannot use a floating-point type as a non-type template parameter. Also, same limitations for other kinds of literals.

    Your lambda would work for that, but I guess you would need a default-capture to get meaningful error message when non-constexpr stuff get passed to the function. That ending std::move is dispensable.

    EDIT2:

    Err, your lambda approach doesn't work for me, I just realized, how it can even work, the lambda is not a constexpr function. It should not be working for you too.

    It seems there's really no way around it but initializing a constexpr variable in local scope.

    EDIT3:

    Oh, ok, my bad, the purpose of the lambda is just the evaluation. So it's working for that. Its result, instead, is which is unusable to follow another compilation time eval.

    EDIT4:

    On C++17, lambdas now can be used in constexpr contexts, so the limitation referred to in EDIT2/EDIT3 is removed! So the lambda solution is the correct one. See this comment for more information.

    0 讨论(0)
提交回复
热议问题