Is it possible to test if a constexpr function is evaluated at compile time?

前端 未结 6 1971
长情又很酷
长情又很酷 2020-12-14 07:02

Since the extended versions of constexpr (I think from C++14) you can declare constexpr functions that could be used as "real" cons

6条回答
  •  清歌不尽
    2020-12-14 07:32

    C++20 introduces is_constant_evaluated, defined in header , which addresses this issue.

    constexpr int foo(int s)
    {
        if (std::is_constant_evaluated()) // note: not "if constexpr"
            /* evaluated at compile time */;
        else
            /* evaluated at run time */;
    }
    

    Note that here the ordinary if is used instead of if constexpr. If you use if constexpr, then the condition has to be evaluated at compile time, so is_constant_evaluated always returns true, rendering the test useless.

提交回复
热议问题