如何正确地对 constexpr 函数进行单元测试

How to properly unit test constexpr functions

本文关键字:单元测试 函数 constexpr 正确地      更新时间:2023-10-16

如果我有一个constexpr函数,是否应该同时进行运行时验证和编译时验证?

如果只有一个编译时检查static_assert,则该函数将不包含在任何代码覆盖率统计信息中。但是,如果只有运行时检查,则不会验证函数是否在constexpr上下文中实际工作。

简而言之,问题是是否需要运行时单元测试和static_assert来测试同一件事。

答案已经存在

https://codereview.stackexchange.com/questions/195282/constexpr-unit-tests-and-asserts

// assertion checking failure
inline constexpr auto your_assert_data(bool isOkay, std::string_view message)
{
if (!isOkay)
throw std::logic_error{message};
}

根据您的问题,您没有尝试过任何东西 所以也看看这个

https://blog.trailofbits.com/2019/06/27/use-constexpr-for-faster-smaller-and-safer-code/