pocoproject / poco

The POCO C++ Libraries are powerful cross-platform C++ libraries for building network- and internet-based applications that run on desktop, server, mobile, IoT, and embedded systems.
https://pocoproject.org
Other
8.05k stars 2.11k forks source link

Poco::Optional iterator to enable "for-each" syntax #4497

Closed nlw0 closed 3 months ago

nlw0 commented 3 months ago

Is your feature request related to a problem? Please describe. Optional and similar types are expected In functional programming languages to be compatible with functors such as map, foreach and flatmap. This makes them very convenient and powerful abstractions. For Poco::Optional it would be interesting to offer a range-based for loop interface. This would allow us to write code such as:

Poco::Optional<int> myint;
myint.assign(7);

if(myint.isSpecified()){
  std::cout << "I have a" << myint.value()<<"\n";
}

as

Poco::Optional<int> myint;
myint.assign(7);

for(auto x: myint) {
  std::cout << "I have a" << x << "\n";
}

Then we can rely a bit more on higher-level language features and focus on the "business logic". Ideally we should rarely have to use isSpecified, and rely instead on functor, lambdas and the "for-each" loop.

The optional type can be seen as a container that can only have either none, or a single value. It should also support map and flatmap. But I offering an iterator and enabling "for-each" loops should be simple to implement and already very useful.

Describe the solution you'd like Implement the necessary methods and iterator type for Poco::Optional to be compatible with range-based for loops ("for-each").

Describe alternatives you've considered One may be able to write some wrapper class. This is potentially a feature many might find advantageous, though.

aleks-f commented 3 months ago

Poco::Optional and Poco::Nullable need a review and reimplementation.

I'd say, since std::optional is part of the standard since c++17, Poco::Optional and Poco::Nullable should be implemented in terms of it (current implementations are inefficient anyways, could/should have been implemented with pointer and the bool flag "wart" avoided; NullType could have been nullptr_t, but even as it is it could have at least been static const).

C++23 adds monadic operations; if I'm understanding it right, that's what you are looking for. We did not yet move to C++23, so we can't introduce it internally at this time, but you could implement those and they can be replaced later once we move to C++23. Does that help?

/cc @matejk

nlw0 commented 3 months ago

I guess Poco::Optional is only really interesting if it's offering an alternative for users of C++14 and earlier. If the project is just targeting C++17 and up, it's probably not really interesting to develop this further. Maybe I'll just create some kind of iterator adapter to scratch my own itch.