From 48c106429a197d9c35c30523d3f5c711f3137333 Mon Sep 17 00:00:00 2001 From: Laurent Pinchart Date: Wed, 27 Jul 2022 23:51:17 +0300 Subject: libcamera: base: utils: Provide defopt to simplify std::optional::value_or() usage The std::optional::value_or(U &&default_value) function returns the contained value if available, or default_value if the std::optional has no value. If the desired default value is a default-constructed T, the obvious option is to call std::optional::value_or(T{}). This approach has two drawbacks: - The \a default_value T{} is constructed even if the std::optional instance has a value, which impacts efficiency. - The T{} default constructor needs to be spelled out explicitly in the value_or() call, leading to long lines if the type is complex. Introduce a defopt variable that solves these issues by providing a value that can be passed to std::optional::value_or() and get implicitly converted to a default-constructed T. Signed-off-by: Laurent Pinchart Reviewed-by: Umang Jain Reviewed-by: Jacopo Mondi --- test/utils.cpp | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) (limited to 'test') diff --git a/test/utils.cpp b/test/utils.cpp index d65467b5..129807a6 100644 --- a/test/utils.cpp +++ b/test/utils.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -169,6 +170,55 @@ protected: return TestPass; } + int testDefopt() + { + static bool defaultConstructed = false; + + struct ValueType { + ValueType() + : value_(-1) + { + defaultConstructed = true; + } + + ValueType(int value) + : value_(value) + { + } + + int value_; + }; + + /* + * Test that utils::defopt doesn't cause default-construction + * of a ValueType instance when value_or(utils::defopt) is + * called on a std::optional that has a value. + */ + std::optional opt = ValueType(0); + ValueType value = opt.value_or(utils::defopt); + + if (defaultConstructed || value.value_ != 0) { + std::cerr << "utils::defopt didn't prevent default construction" + << std::endl; + return TestFail; + } + + /* + * Then test that the ValueType is correctly default-constructed + * when the std::optional has no value. + */ + opt = std::nullopt; + value = opt.value_or(utils::defopt); + + if (!defaultConstructed || value.value_ != -1) { + std::cerr << "utils::defopt didn't cause default construction" + << std::endl; + return TestFail; + } + + return TestPass; + } + int run() { /* utils::hex() test. */ @@ -281,6 +331,10 @@ protected: if (testDuration() != TestPass) return TestFail; + /* utils::defopt test. */ + if (testDefopt() != TestPass) + return TestFail; + return TestPass; } }; -- cgit v1.2.1