/*! @file Defines `boost::hana::overload_linearly`. @copyright Louis Dionne 2013-2016 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_FUNCTIONAL_OVERLOAD_LINEARLY_HPP #define BOOST_HANA_FUNCTIONAL_OVERLOAD_LINEARLY_HPP #include #include #include BOOST_HANA_NAMESPACE_BEGIN //! @ingroup group-functional //! Call the first function that produces a valid call expression. //! //! Given functions `f1, ..., fn`, `overload_linearly(f1, ..., fn)` is //! a new function that calls the first `fk` producing a valid call //! expression with the given arguments. Specifically, //! @code //! overload_linearly(f1, ..., fn)(args...) == fk(args...) //! @endcode //! //! where `fk` is the _first_ function such that `fk(args...)` is a valid //! expression. //! //! //! Example //! ------- //! @include example/functional/overload_linearly.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto overload_linearly = [](auto&& f1, auto&& f2, ..., auto&& fn) { return [perfect-capture](auto&& ...x) -> decltype(auto) { return forwarded(fk)(forwarded(x)...); }; }; #else template struct overload_linearly_t { F f; G g; private: template ()(std::declval()...))> constexpr F const& which(int) const& { return f; } template ()(std::declval()...))> constexpr F& which(int) & { return f; } template ()(std::declval()...))> constexpr F which(int) && { return static_cast(f); } template constexpr G const& which(long) const& { return g; } template constexpr G& which(long) & { return g; } template constexpr G which(long) && { return static_cast(g); } public: template constexpr decltype(auto) operator()(Args&& ...args) const& { return which(int{})(static_cast(args)...); } template constexpr decltype(auto) operator()(Args&& ...args) & { return which(int{})(static_cast(args)...); } template constexpr decltype(auto) operator()(Args&& ...args) && { return which(int{})(static_cast(args)...); } }; struct make_overload_linearly_t { template constexpr overload_linearly_t< typename detail::decay::type, typename detail::decay::type > operator()(F&& f, G&& g) const { return {static_cast(f), static_cast(g)}; } template constexpr decltype(auto) operator()(F&& f, G&& g, H&& ...h) const { return (*this)(static_cast(f), (*this)(static_cast(g), static_cast(h)...)); } template constexpr typename detail::decay::type operator()(F&& f) const { return static_cast(f); } }; constexpr make_overload_linearly_t overload_linearly{}; #endif BOOST_HANA_NAMESPACE_END #endif // !BOOST_HANA_FUNCTIONAL_OVERLOAD_LINEARLY_HPP