我可以使表达式为constexpr吗? [英] Can I make expressions constexpr?

查看:65
本文介绍了我可以使表达式为constexpr吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近写了一些代码,将功能结果打印到 cout .结果本可以在编译时评估,但事实并非如此:

I recently wrote some code which prints a function result to cout. The result could have been evaluated at compile time, but it wasn't:

#include <algorithm>
#include <iostream>

constexpr unsigned int gcd(unsigned int u, unsigned int v)
{
    // ...
}

int main() {
    std::cout << gcd(5, 3) << std::endl;
}

出于各种奇怪的原因,它会编译为:( clang -O3 -std = c ++ 17 )

For whatever bizarre reason, this compiles to: (clang -O3 -std=c++17)

main:
    push    r14
    push    rbx
    push    rax
    mov     edi, 5
    mov     esi, 3
    call    gcd(unsigned int, unsigned int)
    mov     esi, eax
    ...

有关实时示例,请参见编译器资源管理器.

See Compiler Explorer for a live example.

我希望编译器在编译时评估 gcd(5,3),以避免在运行时浪费周期,这显然是可能的.我知道我可以执行以下操作:

I would like the compiler to evaluate gcd(5, 3) at compile time in order to avoid wasting cycles at runtime, which is obviously possible. I know that I could do the following:

int main() {
    constexpr unsigned g = gcd(5, 3); 
    std::cout << g << std::endl;
}

但是,这是不必要的冗长.我想做的就是这样:

However, this is unnecessarily verbose. What I would like to do is simply this:

#define CONSTEVAL(expression) // ...

int main() {
    std::cout << CONSTEVAL(gcd(5, 3)) << std::endl;
}

是否有内置的编译器可以使此 CONSTEVAL 宏成为可能?甚至更好-完全可移植的东西?

Does there exist any kind of compiler builtin that would make this CONSTEVAL macro possible? Or even better - something fully portable?

推荐答案

立即调用的lambda表达式如何?

How about an immediately invoked lambda expression?

#define CONSTEVAL(...) []{ constexpr auto result = __VA_ARGS__; return result; }()

这是产生 constexpr 变量以保存结果并评估该变量的值的有效方法.

This is effectively a way to produce a constexpr variable to hold the result and evaluate to the variable's value.

这也可以通过模板在无宏的情况下完成,但前提是该值可以作为模板参数传递:

This can also be done macro-less via a template, but only if the value can be passed as a template parameter:

template <auto V>
inline constexpr auto consteval_v = V;

用作 consteval_v< gcd(5,3)> .

这篇关于我可以使表达式为constexpr吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆