Skip to content

Commit f52d223

Browse files
committed
Unified interface for result::as<std::optional<T>>
1 parent 68548af commit f52d223

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

include/tao/pq/result.hpp

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,16 @@ namespace tao::pq
3434
class table_writer;
3535
class transaction;
3636

37+
namespace internal
38+
{
39+
template< typename >
40+
inline constexpr bool is_optional = false;
41+
42+
template< typename T >
43+
inline constexpr bool is_optional< std::optional< T > > = true;
44+
45+
} // namespace internal
46+
3747
class result final
3848
{
3949
private:
@@ -226,21 +236,31 @@ namespace tao::pq
226236
[[nodiscard]] auto at( const std::size_t row ) const -> pq::row;
227237

228238
template< typename T >
239+
requires internal::is_optional< T >
229240
[[nodiscard]] auto as() const -> T
230241
{
242+
if( empty() ) {
243+
return std::nullopt;
244+
}
231245
if( size() != 1 ) {
232-
throw std::runtime_error( std::format( "invalid result size: {} rows, expected 1 row", m_rows ) );
246+
throw std::runtime_error( std::format( "invalid result size: {} rows, expected 0 or 1 rows", m_rows ) );
233247
}
234248
return ( *this )[ 0 ].as< T >();
235249
}
236250

237251
template< typename T >
238-
[[nodiscard]] auto optional() const -> std::optional< T >
252+
[[nodiscard]] auto as() const -> T
239253
{
240-
if( empty() ) {
241-
return std::nullopt;
254+
if( size() != 1 ) {
255+
throw std::runtime_error( std::format( "invalid result size: {} rows, expected 1 row", m_rows ) );
242256
}
243-
return as< T >();
257+
return ( *this )[ 0 ].as< T >();
258+
}
259+
260+
template< typename T >
261+
[[nodiscard]] auto optional() const
262+
{
263+
return as< std::optional< T > >();
244264
}
245265

246266
template< typename T, typename U >

0 commit comments

Comments
 (0)