【问题标题】:When to use folly Unit type何时使用愚蠢的单元类型
【发布时间】:2020-05-13 04:17:14
【问题描述】:

在下面的代码 sn-p 中,我看到了这个Unit 类型但不知道什么时候使用它以及它在做什么?我读了这个https://github.com/facebook/folly/blob/master/folly/Unit.h,但仍然不知道如何在我的程序中使用这个单元。单元将提供哪些帮助的典型场景是什么?

   Future<Unit> fut3 = std::move(fut2)
      .thenValue([](string str) {
        cout << str << endl;
      })
      .thenTry([](folly::Try<string> strTry) {
        cout << strTry.value() << endl;
      })
      .thenError(folly::tag_t<std::exception>{}, [](std::exception const& e) {
        cerr << e.what() << endl;
      });

【问题讨论】:

标签: c++ folly


【解决方案1】:

这直接来自comments on the class itself 并解释了几乎所有内容,包括一个用例。

/// In functional programming, the degenerate case is often called "unit". In
/// C++, "void" is often the best analogue. However, because of the syntactic
/// special-casing required for void, it is frequently a liability for template
/// metaprogramming. So, instead of writing specializations to handle cases like
/// SomeContainer<void>, a library author may instead rule that out and simply
/// have library users use SomeContainer<Unit>. Contained values may be ignored.
/// Much easier.
///
/// "void" is the type that admits of no values at all. It is not possible to
/// construct a value of this type.
/// "unit" is the type that admits of precisely one unique value. It is
/// possible to construct a value of this type, but it is always the same value
/// every time, so it is uninteresting.

【讨论】:

  • 投了反对票,因为这篇文章没有回答 OP 问题“何时使用愚蠢的单元类型”,它只是引用了一些文档,这些文档没有解释何时使用该类,并且没有甚至以 OP 能理解的方式解释课程。
【解决方案2】:

folly::Unit 类提供了一个 standard 虚拟类,它是一个真正的类型(与 void 不同),但它本身是无用的,您可以在实例化 pre-现有模板(如 folly::Future)并且您对该模板的实例化不需要或不使用与模板的一个或多个类型名参数对应的对象。当函数模板参数用作函数的返回类型但函数的实例化将具有 void 返回值时,标准的虚拟类型(例如 folly:Unit)特别有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2011-08-24
    • 2012-05-09
    相关资源
    最近更新 更多