C++14: Optional.map in Java 8 for functional programming

less than 1 minute read

Pseudo C++ example implementation of map function of optional in Java8 for functional style programming.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <type_traits>
template <class T>
class Optional {
private:
    T value;
    bool hasValue;
public:
    Optional(T value) : value(value), hasValue(true) {
    }
public:
    T getValue() const {
        return value;
    }
public:
    template<class F>
    auto map(F&& f) -> Optional<std::decay_t<decltype(f(value))>> {
        if (hasValue) {
            return f(value);
        }
        return decltype(f(value))();
    }
};

Exampe

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    auto floatValue = value.map([](int value) -> float {
        return value * 10.0f;
    });
    std::cout << "floatValue: " << floatValue.getValue() << "\n";
    auto stringValue = floatValue.map([](float value) -> std::string {
        return std::to_string(value);
    });
    std::cout << "stringValue: " << stringValue.getValue() << "\n";
    auto finalValue = stringValue.map([](std::string const& value) -> int {
        return std::stoi(value);
    }).map([](int value) -> double {
        return (double)value;
    }).map([](double value) -> std::string {
        std::to_string(value);
    });
    std::cout << "finalValue: " << stringValue.getValue() << "\n";

Categories:

Updated: