diff --git a/include/boost/lambda2/lambda2.hpp b/include/boost/lambda2/lambda2.hpp index 68009a0..d5093dc 100644 --- a/include/boost/lambda2/lambda2.hpp +++ b/include/boost/lambda2/lambda2.hpp @@ -20,6 +20,19 @@ namespace boost namespace lambda2 { +namespace lambda2_detail +{ + +struct subscript +{ + template decltype(auto) operator()(T1&& t1, T2&& t2) const + { + return std::forward(t1)[ std::forward(t2) ]; + } +}; + +} // namespace lambda2_detail + // placeholders template struct lambda2_arg @@ -28,6 +41,11 @@ template struct lambda2_arg { return std::get( std::tuple( std::forward(a)... ) ); } + + template auto operator[]( T&& t ) const + { + return std::bind( lambda2_detail::subscript(), *this, std::forward( t ) ); + } }; #if defined(__cpp_inline_variables) && __cpp_inline_variables >= 201606L diff --git a/test/Jamfile b/test/Jamfile index 48d30cf..1177288 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -22,3 +22,4 @@ run lookup_problem.cpp ; run dereference.cpp ; run placeholders.cpp ; run increment.cpp ; +run subscript.cpp ; diff --git a/test/subscript.cpp b/test/subscript.cpp new file mode 100644 index 0000000..b20eff2 --- /dev/null +++ b/test/subscript.cpp @@ -0,0 +1,27 @@ +// Copyright 2021 Peter Dimov +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#include +#include +#include + +int main() +{ + using namespace boost::lambda2; + + int x[] = { 1, 2, 3, 4 }; + + BOOST_TEST_EQ( _1[0](x), x[0] ); + BOOST_TEST_EQ( _1[_2](x, 1), x[1] ); + BOOST_TEST_EQ( (_1[_2] + _3[_4])(x, 2, x, 3), x[2] + x[3] ); + BOOST_TEST_EQ( std::bind(_1 + _2, _1[_2], _3[_4])(x, 2, x, 3), x[2] + x[3] ); + + _1[0](x) = 7; + BOOST_TEST_EQ( x[0], 7 ); + + _1[_2](x, 1) = 8; + BOOST_TEST_EQ( x[1], 8 ); + + return boost::report_errors(); +}