Add operator&=( result&, unary-returning-value )

This commit is contained in:
Peter Dimov
2023-10-31 02:44:45 +02:00
parent a58115cb50
commit ca5bca39ce
4 changed files with 135 additions and 0 deletions

View File

@ -1118,6 +1118,25 @@ U operator&( result<T, E>&& r, F&& f )
}
}
// operator&=
// result &= unary-returning-value
template<class T, class E, class F,
class U = decltype( std::declval<F>()( std::declval<T>() ) ),
class En1 = typename std::enable_if<!detail::is_result<U>::value>::type,
class En2 = typename std::enable_if<detail::is_value_convertible_to<U, T>::value>::type
>
result<T, E>& operator&=( result<T, E>& r, F&& f )
{
if( r )
{
r = std::forward<F>( f )( *std::move( r ) );
}
return r;
}
} // namespace system
} // namespace boost

View File

@ -174,3 +174,4 @@ boost_test(TYPE run SOURCES result_or_fn0v.cpp)
boost_test(TYPE run SOURCES result_or_fn0r.cpp)
boost_test(TYPE run SOURCES result_and_fn1v.cpp)
boost_test(TYPE run SOURCES result_and_fn1r.cpp)
boost_test(TYPE run SOURCES result_and_eq_fn1v.cpp)

View File

@ -204,3 +204,4 @@ run result_or_fn0v.cpp : : : $(CPP11) ;
run result_or_fn0r.cpp : : : $(CPP11) ;
run result_and_fn1v.cpp : : : $(CPP11) ;
run result_and_fn1r.cpp : : : $(CPP11) ;
run result_and_eq_fn1v.cpp : : : $(CPP11) ;

114
test/result_and_eq_fn1v.cpp Normal file
View File

@ -0,0 +1,114 @@
// Copyright 2017, 2021, 2022 Peter Dimov.
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
#include <boost/system/result.hpp>
#include <boost/core/lightweight_test.hpp>
using namespace boost::system;
struct X
{
int v_;
};
struct Y
{
int v_;
explicit Y( int v ): v_( v ) {}
Y( X x ): v_( x.v_) {}
Y( Y const& ) = delete;
Y& operator=( Y const& ) = delete;
Y( Y&& r ): v_( r.v_ )
{
r.v_ = 0;
}
Y& operator=( Y&& r )
{
if( &r != this )
{
v_ = r.v_;
r.v_ = 0;
}
return *this;
}
};
struct E
{
};
int f( int x )
{
return x * 2 + 1;
}
X g( Y y )
{
return X{ y.v_ * 2 + 1 };
}
int& h( int& )
{
static int x = 2;
return x;
}
int main()
{
{
result<int> r( 1 );
r &= f;
BOOST_TEST( r.has_value() ) && BOOST_TEST_EQ( *r, 3 );
}
{
result<int, E> r( in_place_error );
r &= f;
BOOST_TEST( r.has_error() );
}
{
result<Y> r( in_place_value, 1 );
r &= g;
BOOST_TEST( r.has_value() ) && BOOST_TEST_EQ( r->v_, 3 );
}
{
result<Y, E> r( in_place_error );
r &= g;
BOOST_TEST( r.has_error() );
}
{
int x1 = 1;
result<int&> r( x1 );
r &= h;
BOOST_TEST( r.has_value() ) && BOOST_TEST_EQ( &*r, &h( x1 ) );
}
{
result<int&, E> r( in_place_error );
r &= h;
BOOST_TEST( r.has_error() );
}
return boost::report_errors();
}