相关疑难解决方法(0)

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

请参阅以下代码:

#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的功能?

c++ try-catch constexpr c++11 c++14

1
推荐指数
1
解决办法
225
查看次数

constexpr函数返回类型是非const吗?

我已经读过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.但我不知道这意味着什么.

c++

-3
推荐指数
1
解决办法
917
查看次数

标签 统计

c++ ×2

c++11 ×1

c++14 ×1

constexpr ×1

try-catch ×1