|
| 1 | +// Copyright 2025 The Abseil Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#include "absl/base/casts.h" |
| 16 | + |
| 17 | +#include <type_traits> |
| 18 | +#include <utility> |
| 19 | + |
| 20 | +#include "gtest/gtest.h" |
| 21 | + |
| 22 | +namespace { |
| 23 | + |
| 24 | +struct Base { |
| 25 | + explicit Base(int value) : x(value) {} |
| 26 | + Base(const Base& other) = delete; |
| 27 | + Base& operator=(const Base& other) = delete; |
| 28 | + int x; |
| 29 | +}; |
| 30 | +struct Derived : Base { |
| 31 | + explicit Derived(int value) : Base(value) {} |
| 32 | +}; |
| 33 | + |
| 34 | +static_assert( |
| 35 | + std::is_same_v< |
| 36 | + decltype(absl::implicit_cast<Base&>(std::declval<Derived&>())), Base&>); |
| 37 | +static_assert(std::is_same_v<decltype(absl::implicit_cast<const Base&>( |
| 38 | + std::declval<Derived>())), |
| 39 | + const Base&>); |
| 40 | + |
| 41 | +TEST(ImplicitCastTest, LValueReference) { |
| 42 | + Derived derived(5); |
| 43 | + EXPECT_EQ(&absl::implicit_cast<Base&>(derived), &derived); |
| 44 | + EXPECT_EQ(&absl::implicit_cast<const Base&>(derived), &derived); |
| 45 | +} |
| 46 | + |
| 47 | +TEST(ImplicitCastTest, RValueReference) { |
| 48 | + Derived derived(5); |
| 49 | + Base&& base = absl::implicit_cast<Base&&>(std::move(derived)); |
| 50 | + EXPECT_EQ(&base, &derived); |
| 51 | + |
| 52 | + const Derived cderived(6); |
| 53 | + const Base&& cbase = absl::implicit_cast<const Base&&>(std::move(cderived)); |
| 54 | + EXPECT_EQ(&cbase, &cderived); |
| 55 | +} |
| 56 | + |
| 57 | +} // namespace |
0 commit comments