请参阅以下代码:
#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的功能?
我已经读过constexpr函数返回类型可以是非常量的,在我的书中也有这样的代码:
constexpr bool isShorter(const string& str1, const string& str2)
{
return str1.size() < str2.size();
}
Run Code Online (Sandbox Code Playgroud)
但是在str1.size()这下面有一个错误:constexpr函数返回是非常量的.根据这本书,它必须是正确的,但编译器不同意.
每次我constexpr在不同的代码中使用时总会出现这样的错误:缺少类型说明符 - 假设为int.注意:C++不支持default-int.但我不知道这意味着什么.