1

在下面的代码片段中,我看到了这种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;
      });
4

2 回答 2

2

这直接来自对类本身的评论,并解释了几乎所有内容,包括一个用例。

/// 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.
于 2020-01-27T19:05:41.390 回答
0

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

于 2020-12-01T11:49:38.680 回答