Line data Source code
1 : /********************************************************************** 2 : * 3 : * Name: cpl_int_wrapper.h 4 : * Project: CPL - Common Portability Library 5 : * Purpose: Strongly typed wrapper around int 6 : * Author: Even Rouault <even dot rouault at spatialys.com> 7 : * 8 : ****************************************************************************** 9 : * Copyright (c) 2026, Even Rouault <even dot rouault at spatialys.com> 10 : * 11 : * SPDX-License-Identifier: MIT 12 : ****************************************************************************/ 13 : 14 : #ifndef CPL_INT_WRAPPER_H_INCLUDED 15 : #define CPL_INT_WRAPPER_H_INCLUDED 16 : 17 : namespace cpl 18 : { 19 : /** Strongly typed wrapper around an integer data type. 20 : * 21 : * Template parameter TagType is typically a tag structure (``struct MyTag{};``) 22 : */ 23 : template <class TagType, typename IntType = int> class IntWrapper 24 : { 25 : IntType m_value; 26 : 27 : public: 28 : /** Constructor */ 29 : // cppcheck-suppress noExplicitConstructor 30 29637 : inline constexpr IntWrapper(IntType v) : m_value(v) 31 : { 32 29637 : } 33 : 34 : /** Cast to integer */ 35 37930 : inline constexpr explicit operator IntType() const 36 : { 37 37930 : return m_value; 38 : } 39 : 40 : /*! @cond Doxygen_Suppress */ 41 : 42 78 : inline IntWrapper operator+(IntType value) const 43 : { 44 78 : return m_value + value; 45 : } 46 : 47 4277 : inline IntWrapper &operator++() // prefix ++x 48 : { 49 4277 : ++m_value; 50 4277 : return *this; 51 : } 52 : 53 : #define COMPARISON_OPERATOR(op) \ 54 : inline bool operator op(const IntWrapper &other) const \ 55 : { \ 56 : return m_value op other.m_value; \ 57 : } 58 10496 : COMPARISON_OPERATOR(==) 59 8325 : COMPARISON_OPERATOR(!=) 60 117606 : COMPARISON_OPERATOR(<) 61 2129 : COMPARISON_OPERATOR(<=) 62 : COMPARISON_OPERATOR(>) 63 : COMPARISON_OPERATOR(>=) 64 : #undef COMPARISON_OPERATOR 65 : 66 : #define COMPARISON_OPERATOR(op) \ 67 : inline bool operator op(IntType value) const \ 68 : { \ 69 : return m_value op value; \ 70 : } 71 1602 : COMPARISON_OPERATOR(==) 72 145 : COMPARISON_OPERATOR(!=) 73 7487 : COMPARISON_OPERATOR(<) 74 2132 : COMPARISON_OPERATOR(<=) 75 4759 : COMPARISON_OPERATOR(>) 76 4261 : COMPARISON_OPERATOR(>=) 77 : #undef COMPARISON_OPERATOR 78 : /*! @endcond */ 79 : }; 80 : 81 : } // namespace cpl 82 : 83 : #endif // CPL_INT_WRAPPER_H_INCLUDED