首页 > 解决方案 > 有什么方法可以移动在使用它的结构内返回 std::optional 的 constexpr 函数?

问题描述

我知道问题的标题令人困惑,所以这里是示例:

#include<array>
#include<optional>
#include<type_traits>

static constexpr std::optional<int> maybe_int() {
    return  {64};
}
struct s {

    using type = std::conditional_t< maybe_int().has_value(), std::array<int, *maybe_int()>,float > ;
};
static_assert(std::is_same_v<s::type, std::array<int,64>>);

这段代码编译得很好,但是当我maybe_int进入 struct 编译失败时。

错误:'static constexpr std::optional<int> s::maybe_int()' 在定义完成之前在常量表达式中调用

请注意,我知道代码可以与自由功能一起正常工作,这是关于可读性的。所以我想maybe_int在 struct 里面移动。

标签: c++constexprstdoptional

解决方案


推荐阅读