From d426ef265a764359d16097c42d1357c19b01e218 Mon Sep 17 00:00:00 2001 From: Martin Moene Date: Tue, 10 Dec 2024 14:53:15 +0100 Subject: [PATCH] Mark expected as [[nodiscard]] (default), control via nsel_CONFIG_NO_NODISCARD (#74, thanks Quuxplusone) --- README.md | 5 +++++ include/nonstd/expected.hpp | 21 ++++++++++++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e83392a..bf33eb8 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,11 @@ Define this to 1 if you want to compile without exceptions. If not defined, the -Dnsel\_CONFIG\_NO\_EXCEPTIONS\_SEH=0 Define this to 1 or 0 to control the use of SEH when C++ exceptions are disabled (see above). If not defined, the header tries and detect if SEH is available if C++ exceptions have been disabled (e.g. via `-fno-exceptions` or `/kernel`). Default determined in header. +#### Disable \[\[nodiscard\]\] + +-Dnsel\_CONFIG\_NO\_NODISCARD=0 +Define this to 1 if you want to compile without \[\[nodiscard\]\]. Note that the default of marking `class expected` with \[\[nodiscard\]\] is not part of the C++23 standard. The rationale to use \[\[nodiscard\]\] is that unnoticed discarded expected error values may break the error handling flow. + #### Enable compilation errors \-Dnsel\_CONFIG\_CONFIRMS\_COMPILATION\_ERRORS=0 diff --git a/include/nonstd/expected.hpp b/include/nonstd/expected.hpp index a0385d0..54960a2 100644 --- a/include/nonstd/expected.hpp +++ b/include/nonstd/expected.hpp @@ -89,6 +89,14 @@ # define nsel_CONFIG_WIN32_LEAN_AND_MEAN 0 #endif +// Control marking class expected with [[nodiscard]]]: + +#if !defined(nsel_CONFIG_NO_NODISCARD) +# define nsel_CONFIG_NO_NODISCARD 0 +#else +# define nsel_CONFIG_NO_NODISCARD 1 +#endif + // Control presence of C++ exception handling (try and auto discover): #ifndef nsel_CONFIG_NO_EXCEPTIONS @@ -429,6 +437,7 @@ nsel_DISABLE_MSVC_WARNINGS( 26409 ) // Presence of C++17 language features: #define nsel_HAVE_DEPRECATED nsel_CPP17_000 +#define nsel_HAVE_NODISCARD nsel_CPP17_000 // C++ feature usage: @@ -438,6 +447,12 @@ nsel_DISABLE_MSVC_WARNINGS( 26409 ) # define nsel_deprecated(msg) /*[[deprecated]]*/ #endif +#if nsel_HAVE_NODISCARD && !nsel_CONFIG_NO_NODISCARD +# define nsel_NODISCARD [[nodiscard]] +#else +# define nsel_NODISCARD /*[[nodiscard]]*/ +#endif + // // expected: // @@ -459,7 +474,7 @@ namespace std11 { } template< class T > - const T * addressof( const T && ) = delete; + const T * addressof( const T && ) = delete; #endif } // namespace std11 @@ -1824,10 +1839,10 @@ namespace expected_lite { #if nsel_P0323R <= 2 template< typename T, typename E = std::exception_ptr > -class expected +class nsel_NODISCARD expected #else template< typename T, typename E > -class expected +class nsel_NODISCARD expected #endif // nsel_P0323R { private: