File tree Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -325,6 +325,14 @@ template <typename ContainerTy> bool hasSingleElement(ContainerTy &&C) {
325
325
return B != E && std::next (B) == E;
326
326
}
327
327
328
+ // / Asserts that the given container has a single element and returns that
329
+ // / element.
330
+ template <typename ContainerTy>
331
+ decltype (auto ) getSingleElement(ContainerTy &&C) {
332
+ assert (hasSingleElement (C) && " expected container with single element" );
333
+ return *adl_begin (C);
334
+ }
335
+
328
336
// / Return a range covering \p RangeOrContainer with the first N elements
329
337
// / excluded.
330
338
template <typename T> auto drop_begin (T &&RangeOrContainer, size_t N = 1 ) {
Original file line number Diff line number Diff line change @@ -1016,6 +1016,28 @@ TEST(STLExtrasTest, hasSingleElement) {
1016
1016
EXPECT_FALSE (hasSingleElement (S));
1017
1017
}
1018
1018
1019
+ TEST (STLExtrasTest, getSingleElement) {
1020
+ // Note: Asserting behavior of getSingleElement cannot be tested because the
1021
+ // program would crash.
1022
+ const std::vector<int > V1 = {7 };
1023
+ EXPECT_EQ (getSingleElement (V1), 7 );
1024
+
1025
+ std::vector<int > V2 = {8 };
1026
+ EXPECT_EQ (getSingleElement (V2), 8 );
1027
+
1028
+ SmallVector<int > V3 {9 };
1029
+ EXPECT_EQ (getSingleElement (V3), 9 );
1030
+
1031
+ std::list<int > L1 = {10 };
1032
+ EXPECT_EQ (getSingleElement (L1), 10 );
1033
+
1034
+ // Make sure that we use the `begin`/`end` functions from `some_namespace`,
1035
+ // using ADL.
1036
+ some_namespace::some_struct S;
1037
+ S.data = V2;
1038
+ EXPECT_EQ (getSingleElement (S), 8 );
1039
+ }
1040
+
1019
1041
TEST (STLExtrasTest, hasNItems) {
1020
1042
const std::list<int > V0 = {}, V1 = {1 }, V2 = {1 , 2 };
1021
1043
const std::list<int > V3 = {1 , 3 , 5 };
You can’t perform that action at this time.
0 commit comments