【发布时间】: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