Learning about the Expected and ErrorOr classes
As we briefly mentioned in the introduction of this section, in LLVM's code base it's pretty common to see a coding pattern where an API wants to return a result or an error if something goes wrong. LLVM tries to make this pattern more accessible by creating utilities that multiplex results and errors in a single object—they are the Expected
and ErrorOr
classes. Let's begin with the first one.
The Expected class
The Expected
class carries either a Success
result or an error—for instance, the JSON library in LLVM uses it to represent the outcome of parsing an incoming string, as shown next:
#include "llvm/Support/JSON.h" using namespace llvm; … // `InputStr` has the type of `StringRef` Expected<json::Value> JsonOrErr = json::parse(InputStr); if (JsonOrErr) {   // Success!   json::Value &Json = *JsonOrErr;   … } else {   // Something...