From 6ecba3c7ff58bf0d28775384edd299753dbf43be Mon Sep 17 00:00:00 2001 From: Christoph Klee Date: Mon, 12 Dec 2022 19:23:43 +0000 Subject: [PATCH] pw_vector: Add constexpr max_size() for fixed-sized vector This change introduces the max_size() function for the fixed-sized vector implementation. By declaring it as static constexpr we can use the max_size of a fixed-size vector to size another vector at compile time. If only the generic vector gets passed to a function, the generic max_size function gets called, that won't return the constexpr max size value. Tested: Added ConstexprMaxSize test case Change-Id: I45ea288d756641e108103c4e0ce958759876e32a Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/122891 Reviewed-by: Wyatt Hepler Commit-Queue: Christoph Klee --- pw_containers/public/pw_containers/vector.h | 2 ++ pw_containers/vector_test.cc | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/pw_containers/public/pw_containers/vector.h b/pw_containers/public/pw_containers/vector.h index 996b9acac4..853e1ebec1 100644 --- a/pw_containers/public/pw_containers/vector.h +++ b/pw_containers/public/pw_containers/vector.h @@ -114,6 +114,8 @@ class Vector : public Vector { Vector(std::initializer_list list) : Vector(kMaxSize, list) {} + static constexpr size_t max_size() { return kMaxSize; } + // Construct from std::string_view when T is char. template >> diff --git a/pw_containers/vector_test.cc b/pw_containers/vector_test.cc index 99694a44d3..e90da6f2ed 100644 --- a/pw_containers/vector_test.cc +++ b/pw_containers/vector_test.cc @@ -488,6 +488,19 @@ TEST(Vector, Generic) { } } +TEST(Vector, ConstexprMaxSize) { + Vector vector; + Vector vector2; + + EXPECT_EQ(vector.max_size(), vector2.max_size()); + + // The following code would fail with the following compiler error: + // "non-type template argument is not a constant expression" + // Reason: the generic_vector doesn't return a constexpr max_size value. + // Vector& generic_vector(vector); + // Vector vector3; +} + // Test that Vector is trivially destructible when its type is. static_assert(std::is_trivially_destructible_v>); static_assert(std::is_trivially_destructible_v>);