From 78f04ad2982a11a7a9f0166526726ca151c8fbef Mon Sep 17 00:00:00 2001 From: Helder Duarte Date: Thu, 27 Nov 2025 08:48:27 +0000 Subject: [PATCH] Fix value_or not taking const in optional (#1225) --- include/etl/optional.h | 8 ++++---- test/test_optional.cpp | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/include/etl/optional.h b/include/etl/optional.h index 45cb5f92..3b565c5b 100644 --- a/include/etl/optional.h +++ b/include/etl/optional.h @@ -471,7 +471,7 @@ namespace etl etl::enable_if_t::value, T> value_or(U&& default_value) const& { - return has_value() ? value() : etl::forward(default_value); + return has_value() ? value() : static_cast(etl::forward(default_value)); } //*************************************************************************** @@ -482,7 +482,7 @@ namespace etl etl::enable_if_t::value, T> value_or(U&& default_value)&& { - return has_value() ? etl::move(value()) : etl::forward(default_value); + return has_value() ? etl::move(value()) : static_cast(etl::forward(default_value)); } #endif @@ -1085,7 +1085,7 @@ namespace etl etl::enable_if_t::value, T> value_or(U&& default_value) const& { - return has_value() ? value() : etl::forward(default_value); + return has_value() ? value() : static_cast(etl::forward(default_value)); } //*************************************************************************** @@ -1096,7 +1096,7 @@ namespace etl etl::enable_if_t::value, T> value_or(U&& default_value)&& { - return has_value() ? etl::move(value()) : etl::forward(default_value); + return has_value() ? etl::move(value()) : static_cast(etl::forward(default_value)); } #endif diff --git a/test/test_optional.cpp b/test/test_optional.cpp index c5a34d08..42ab7199 100644 --- a/test/test_optional.cpp +++ b/test/test_optional.cpp @@ -298,6 +298,21 @@ namespace CHECK_EQUAL(Data("Value"), result); } + //************************************************************************* + TEST(test_value_or_const) + { + using FundamentalType = int; + using NonFundamentalType = std::string; + + const FundamentalType constFT{ 5 }; + int resultFT = etl::optional{}.value_or(constFT); + CHECK_EQUAL(5, resultFT); + + const NonFundamentalType constNFT{ "Default" }; + NonFundamentalType resultNFT = etl::optional{}.value_or(constNFT); + CHECK_EQUAL("Default", resultNFT); + } + //************************************************************************* struct github_bug_720_bug_helper {