Line data Source code
1 : /* 2 : * 3 : * Copyright (c) 2021 Project CHIP Authors 4 : * 5 : * Licensed under the Apache License, Version 2.0 (the "License"); 6 : * you may not use this file except in compliance with the License. 7 : * You may obtain a copy of the License at 8 : * 9 : * http://www.apache.org/licenses/LICENSE-2.0 10 : * 11 : * Unless required by applicable law or agreed to in writing, software 12 : * distributed under the License is distributed on an "AS IS" BASIS, 13 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 : * See the License for the specific language governing permissions and 15 : * limitations under the License. 16 : */ 17 : 18 : /** 19 : * @file 20 : * This file defines and implements a number of miscellaneous 21 : * templates for simplify code with handling types. 22 : * 23 : */ 24 : 25 : #pragma once 26 : 27 : #include <type_traits> 28 : 29 : namespace chip { 30 : 31 : /** 32 : * @brief Implemented std::to_underlying introduced in C++23. 33 : */ 34 : template <class T> 35 844368 : constexpr std::underlying_type_t<T> to_underlying(T e) 36 : { 37 : static_assert(std::is_enum<T>::value, "to_underlying called to non-enum values."); 38 844368 : return static_cast<std::underlying_type_t<T>>(e); 39 : } 40 : 41 : /** 42 : * @brief This template is not designed to be used directly. A common pattern to check the presence of a member of a class is: 43 : * 44 : * \cond 45 : * template <typename T> 46 : * class IsMagic 47 : * { 48 : * private: 49 : * template <typename Tp> 50 : * static auto TestHasMagic(int) -> TemplatedTrueType<decltype(&Tp::Magic)>; 51 : * 52 : * template <typename Tp> 53 : * static auto TestHasMagic(long) -> std::false_type; 54 : * 55 : * public: 56 : * static constexpr bool value = decltype(TestHasMagic<std::decay_t<T>>(0))::value; 57 : * }; 58 : * \endcond 59 : * 60 : * The compiler will try to match TestHasMagicFunction(int) first, if MagicFunction is a member function of T, the match succeed 61 : * and HasMagicFunction is an alias of std::true_type. If MagicFunction is not a member function of T, the match of 62 : * TestHasMagicFunction(int) will result in compile error, due to SFINAE, compiler will try the next candicate, which is 63 : * TestHasMagicFunction(long), it will always success for all types, and HasMagicFunction becomes an alias of std::false_type. 64 : */ 65 : template <typename T> 66 : using TemplatedTrueType = std::true_type; 67 : 68 : } // namespace chip