代码之家  ›  专栏  ›  技术社区  ›  Incomputable

如何使lambda与STD::nulLopt

  •  3
  • Incomputable  · 技术社区  · 7 年前

    背景

    我有一系列lambda,它们对捕获的变量执行不同的检查并返回 std::nullopt 如果检查失败。 return std::nullopt 是第一个返回语句。然后,如果检查成功,他们继续计算值。

    问题

    返回表达式的类型不一致,例如。 std::nullopt_t 无法转换为 std::optional<T> 即使反过来也行。特别是,我希望编译并运行以下代码,打印2:

    #include <functional>
    #include <utility>
    #include <optional>
    
    int x = 3;
    
    auto lambda = [](){
        if (x == 2)
            return std::nullopt;
    
        return std::optional(2);
    };
    
    #include <iostream>
    
    int main () {
        using return_type = std::invoke_result_t<decltype(lambda)>;
        static_assert(std::is_same<return_type, std::optional<int>>{}, 
                      "return type is still std::nullopt_t");
    
        std::cout << lambda().value() << '\n';
    }
    

    Wandbox Demo .

    思想

    我相信我需要用 std::common_type<Args...> 在某个地方,但我既不能强迫它出现,也不能推断 Args ,因为它可能需要语言支持。

    2 回复  |  直到 7 年前
        1
  •  5
  •   Rakete1111    7 年前

    与其使用模板类型推断来推断lambda的返回类型,为什么不显式指定该返回类型?

    auto lambda = []() -> std::optional<int> {
        if (x == 2)
            return std::nullopt;
    
        return 2;
    };
    

    std::common_type 通常使用模板,但您没有模板。

        2
  •  1
  •   user7860670    7 年前

    我建议只使用一个返回语句和显式指定的结果类型,而不使用nullopt。当函数返回整数或nullopt时,这看起来有点误导。尤其是功能更长的时候。如果值类型是具有显式构造函数的,则使用 emplace 允许避免再次键入值类型名称。

    auto lambda = []()
    {
        std::optional<int> result{};
        if(2 != x)
        {
            result.emplace(2);
        }
        return result;
    };
    
    推荐文章