gpt4 book ai didi

c++ - 使用 consteval 代替 constexpr 函数有什么优点?

转载 作者:行者123 更新时间:2023-12-03 06:56:00 31 4
gpt4 key购买 nike

我知道需求的差异,我最感兴趣的是它带来的代码质量带来的好处。
我能想到的几件事:

  • reader 可以读取函数签名并知道函数在编译时被评估
  • 编译器可能会发出更少的代码,因为 consteval fns 在运行时从不使用(这是推测性的,我没有这方面的真实数据)
  • 不需要有变量来强制 ctfe ,最后的例子

  • 注意:如果代码质量太模糊,我理解有些人可能想要结束这个问题,对我来说代码质量并不是那么模糊的术语,但是......
    example 其中 constexpr 故障延迟到运行时:
    constexpr int div_cx(int a, int b)
    {
    assert(b!=0);
    return a/b;
    }

    int main()
    {
    static constexpr int result = div_cx(5,0); // compile time error, div by 0
    std::cout << result;
    std::cout << div_cx(5,0) ; // runtime error :(
    }

    最佳答案

    为了获得有意义的、有意义的静态反射(编译时反射),您需要一种在编译时执行代码的方法。最初的静态反射 TS 提案使用了传统的模板元编程技术,因为它们是在编译时执行代码的唯一有效工具。
    但是,随着 constexpr 代码获得更多功能,通过 constexpr 函数进行编译时静态反射变得越来越可行。这种想法的一个问题是不允许静态反射值泄漏到非编译时代码中。
    我们需要能够编写只能在编译时执行的代码。对于函数中间的一小段代码,很容易做到这一点;该代码的运行时版本根本不包含反射部分,只包含它们的结果。
    但是,如果您想编写一个接受反射值并返回反射值的函数呢?还是反射值列表?
    该函数不能是 constexpr ,因为 constexpr 函数必须能够在运行时执行。您可以执行诸如获取指向 constexpr 函数的指针之类的操作,并以编译器无法跟踪的方式调用它们,从而强制它在运行时执行。
    采用反射值的函数不能这样做。它必须仅在编译时执行。所以 constexpr 不适合这样的函数。
    输入 consteval :一个函数,即 "required" to execute only at compile time 。有一些特定的规则使指向此类函数的指针不可能泄漏到运行时代码等中。
    因此,consteval 目前没有太多用途。它在 a few places like source_location::current() , 中使用,从根本上说在运行时执行是没有意义的。但最终,该功能是进一步编译时编程工具尚不存在的必要构建块。
    这是在 paper that originally proposed this feature 中规定的:

    The impetus for the present paper, however, is the work being done by SG7 in the realm of compile-time reflection. There is now general agreement that future language support for reflection should use constexpr functions, but since "reflection functions" typically have to be evaluated at compile time, they will in fact likely be immediate functions.

    关于c++ - 使用 consteval 代替 constexpr 函数有什么优点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64741639/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com