Understand Internals of std::expected -- Bartlomiej Filipek

BartlomiejFilipek-expected.pngIn the article about std::expected, I introduced the type and showed some basic examples, and in this text, you’ll learn how it is implemented.

Understand Internals of std::expected

by Bartlomiej Filipek

From the article:

In short, std::expected should contain two data members: the actual expected value and the unexpected error object. So, in theory, we could use a simple structure:

template <class _Ty, class _Err> 
struct expected {  
     /*... lots of code ... */  
     _Ty _Value;  
     _Err _Unexpected; 
}; 

However, there are better solutions than this. Here are some obvious issues for our “struct” approach.

  • The size of the object is the sum of the Value type and the Error type (plus padding if needed).
  • Two data members are “active” and initialized, which might not be possible - for example, what if the Value type has no default constructor? The Standard requires that std::expected" holds either a value of type Tor an error of typeE` within its storage.
  • We’d have to guarantee that _Ty cannot be a reference type or an array type; it must be a Destructible Type.
  • Similarly for the _Err type we have to guarantee that it’s also Destructible, and must be a valid template argument for std::unexpected (so not an array, non-object type, nor cv-qualified type).
  • Plus, we’d have to write a lot of code that creates an API for the type

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.