iceberg-cpp
Loading...
Searching...
No Matches
checked_cast.h
Go to the documentation of this file.
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20#pragma once
21
26
27#include <memory>
28#include <type_traits>
29#include <utility>
30
31namespace iceberg::internal {
32
33template <typename OutputType, typename InputType>
34inline OutputType checked_cast(InputType&& value) {
35 static_assert(
36 std::is_class_v<std::remove_pointer_t<std::remove_reference_t<InputType>>>,
37 "checked_cast input type must be a class");
38 static_assert(
39 std::is_class_v<std::remove_pointer_t<std::remove_reference_t<OutputType>>>,
40 "checked_cast output type must be a class");
41#ifdef NDEBUG
42 return static_cast<OutputType>(value);
43#else
44 return dynamic_cast<OutputType>(value);
45#endif
46}
47
48template <class T, class U>
49std::shared_ptr<T> checked_pointer_cast(std::shared_ptr<U> r) noexcept {
50#ifdef NDEBUG
51 return std::static_pointer_cast<T>(std::move(r));
52#else
53 return std::dynamic_pointer_cast<T>(std::move(r));
54#endif
55}
56
57template <class T, class U>
58std::unique_ptr<T> checked_pointer_cast(std::unique_ptr<U> r) noexcept {
59#ifdef NDEBUG
60 return std::unique_ptr<T>(static_cast<T*>(r.release()));
61#else
62 return std::unique_ptr<T>(dynamic_cast<T*>(r.release()));
63#endif
64}
65
66} // namespace iceberg::internal