在运行时调用处理constexpr.C++

Edu*_*yan 1 c++ try-catch constexpr c++11 c++14

请参阅以下代码:

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道constexprt函数在编译时处理.那么我怎么能将"运行时"本地变量传递给它并在运行时再次在try-catch块中使用它?也许我错过了smth regargind constexprt的功能?

Sto*_*ica 5

我知道constexprt函数在编译时处理.

不准确的.甲constexpr函数可以被用于其中的常量表达式需要,如果分对齐.这意味着它必须满足某些要求,但它仍然是一个功能.你仍然可以将它作为一个使用.

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

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