如何解决为什么对constexpr中无法访问的代码进行评估?
我曾希望编译器在涉及constexpr的不可达代码中允许无效或错误语句,如果:
#include <type_traits>
#include <iostream>
struct ret_t;
struct only_declared_t;
auto test = [](auto a) {
if constexpr(std::is_invocable_r_v<ret_t,decltype(a),int>) {
return a(42);
} else {
return 42;
}
// I expect to never reach that statement,but the compiler complains
static_assert(false,"This code should never be reached.");
return only_declared{};
};
int main() {
std::cerr << "Result is " << test(10) << "\n";
}
任何解释/解决方法都会有所帮助
解决方法
static_assert
在编译时工作,因此无论代码是否可到达,它都会生成编译时错误。您可以使用assert
进行运行时检查。 assert
不会被评估。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。