concept sum type in category c++

appears as: The sum types, The sum type, sum types, sum type, sum type
Functional Programming in C++

This is an excerpt from Manning's book Functional Programming in C++.

The sum types aren’t as prominent in C++ as product types. The sum type of types A and B is a type that can hold an instance of A or an instance of B, but not both at the same time.

Enums as sum types

Enums are a special kind of sum type. You define an enum by specifying the different values it can hold. An instance of that enum type can hold exactly one of those values. If you treat these values as one-element sets, the enum is a sum type of those sets.

You can think of sum types as a generalization of an enum. Instead of providing one-element sets when defining the sum type, you specify sets with an arbitrary number of elements.

In the example scenario, you have three main states: the initial state, the counting state, and the finished state. The initial state doesn’t need to contain any additional information, the counting state contains a counter and the handler for accessing the web page, and the finished state needs to contain only the final word count. Because these states are mutually exclusive, when you write the program for this scenario, you can model the state by creating a sum type of three types—one type for each state.

Listing 9.1 Tagged superclass for creating sum types through inheritance
class state_t {
protected:    #1  
    state_t(int type)    #2  
       : type(type)    #2  
    {
    }

public:
    virtual ~state_t() {};
    int type;

};

#1   It shouldn’t be possible to create instances of this class, so make the constructor protected. It can be called only by classes that inherit from state_t.
#2   Each subclass should pass a different value for the type argument. You can use it as an efficient replacement for dynamic_cast.
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest