【问题标题】:Calling processing constexpr at runtime. C++ [duplicate]在运行时调用处理 constexpr。 C++ [重复]
【发布时间】:2018-08-07 00:26:27
【问题描述】:

请看下面的代码:

#include <iostream>

constexpr int f(int a, int b)
{
    return a<b? a : throw std::out_of_range("out of range");    
}

int main() 
{
    try
    {
        int n = 0;
        f(5, n);
    }
    catch(const std::exception& ex)
    {
        std::cout<<"Exception caught"<<std::endl;
        std::cout<<ex.what()<<std::endl;
    }
}

我知道 constexprt 函数是在编译时处理的。那么我是如何将“运行时”本地变量传递给它并在运行时再次在 try-catch 块中使用它的呢?也许我错过了 constexprt 函数?

【问题讨论】:

  • 当 constexpr 函数在编译期间使用一个或多个未知值调用时,它的行为与普通函数一样。这意味着它在运行时计算结果。你不需要两个函数来执行相同的操作,

标签: c++ c++11 try-catch c++14 constexpr


【解决方案1】:

我知道 constexprt 函数是在编译时处理的。

不准确。 constexpr 函数可以用于需要常量表达式的地方,如果星星对齐的话。这意味着它必须满足某些要求,但它仍然是一个函数。而且你仍然可以将它作为一个整体使用。

在您的情况下,该函数是在运行时编译和调用的。

如果您要在需要常量表达式的地方使用它,并且使用了带有throw 的分支,那么您会看到一系列问题。

【讨论】:

    猜你喜欢
    • 2016-10-31
    • 1970-01-01
    • 2013-04-07
    • 2019-12-27
    • 2019-03-20
    • 1970-01-01
    • 2020-11-17
    • 2012-08-20
    • 2018-12-15
    相关资源
    最近更新 更多