什么时候constexpr函数在编译时得到求值? [英] When does a constexpr function get evaluated at compile time?

查看:186
本文介绍了什么时候constexpr函数在编译时得到求值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为可能在运行时调用一个声明为constexpr的函数,编译器根据哪个标准决定是在编译时还是在运行时计算它?

 模板< typename base_t,typename expo_t> 
constexpr base_t POW(base_t base,expo_t expo)
{
return(expo!= 0)? base * POW(base,expo -1):1;
}

int main(int argc,char ** argv)
{
int i = 0;
std :: cin>>一世;

std :: cout<< POW(i,2)< std :: endl;
return 0;
}

在这种情况下,i在编译时是未知的,为什么编译器将POW()视为在运行时调用的常规函数​​。然而,这种动态,尽可能方便,似乎是,有一些不切实际的影响。例如,可能有一种情况,我想编译器计算一个constexpr函数在编译期,编译器决定将其视为一个正常的函数,而它将在编译时工作吗?是否有任何已知的常见错误?

解决方案

constexpr 将在编译时评估,当其所有参数都是常量表达式,并且结果也在常量表达式中使用。常量表达式可以是一个字面量(如 42 ),一个非类型模板参数(如 N 元素声明(例如 Blue(c $ c> template class array; ), enum 中枚举颜色{Red,Blue,Green}; ,另一个变量声明为 constexpr p>

当它的所有参数都是常量表达式并且结果不是在常量表达式中使用时,可以对它们进行求值,但是这是由实施。


Since it is possible that a function declared as constexpr can be called during run-time, under which criteria does the compiler decide whether to compute it at compile-time or during runtime?

template<typename base_t, typename expo_t>
constexpr base_t POW(base_t base, expo_t expo)
{
    return (expo != 0 )? base * POW(base, expo -1) : 1;
}

int main(int argc, char** argv)
{
    int i = 0;
    std::cin >> i;

    std::cout << POW(i, 2) << std::endl;
    return 0;
}

In this case, i is unknown at compile-time, which is probably the reason why the compiler treats POW() as a regular function which is called at runtime. This dynamic however, as convenient as it may appear to be, has some impractical implications. For instance, could there be a case where I would like the compiler to compute a constexpr function during compile-time, where the compiler decides to treat it as a normal function instead, when it would have worked during compile-time as well? Are there any known common pitfalls?

解决方案

constexpr functions will be evaluated at compile time when all its arguments are constant expressions and the result is used in a constant expression as well. A constant expression could be a literal (like 42), a non-type template argument (like N in template<class T, size_t N> class array;), an enum element declaration (like Blue in enum Color { Red, Blue, Green };, another variable declared constexpr, and so on.

They might be evaluated when all its arguments are constant expressions and the result is not used in a constant expression, but that is up to the implementation.

这篇关于什么时候constexpr函数在编译时得到求值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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