微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么对constexpr中无法访问的代码进行评估?

如何解决为什么对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 举报,一经查实,本站将立刻删除。