Моя реализация:
Это моя реализация для «замены» типа int, другие типы реализованы таким же образом, но для краткости я просто поделюсь типом int. (в моем исходном коде я реализовал это с помощью макросов).
Код: Выделить всё
struct i32 {
constexpr i32() = default;
constexpr i32(int32_t v) : value(v) {}
constexpr i32(const i32& b) = default;
constexpr i32(i32&& b) noexcept : value(std::exchange(b.value, 0)) {}
~i32() = default;
constexpr auto operator=(const i32& b) -> i32& {
if(this != &b) {
value = b.value;
}
return *this;
}
constexpr auto operator=(i32&& b) noexcept -> i32& {
if(this != &b) {
value = std::exchange(b.value, 0);
}
return *this;
}
constexpr auto operator+=(int32_t x) -> i32& {
value += x;
return *this;
}
constexpr auto operator-=(int32_t x) -> i32& {
value -= x;
return *this;
}
constexpr auto operator*=(int32_t x) -> i32& {
value *= x;
return *this;
}
constexpr auto operator%=(int32_t x) -> i32& {
value %= x;
return *this;
}
constexpr auto operator&=(int32_t x) -> i32& {
value &= x;
return *this;
}
constexpr auto operator|=(int32_t x) -> i32& {
value |= x;
return *this;
}
constexpr auto operator^=(int32_t x) -> i32& {
value ^= x;
return *this;
}
constexpr auto operator i32& {
value >>= x;
return *this;
}
constexpr auto operator/=(int32_t x) -> i32& {
value /= x;
return *this;
}
constexpr auto operator++() -> i32& {
++value;
return *this;
}
constexpr auto operator++(int) -> i32 {
i32 tmp(*this);
++(*this);
return tmp;
}
constexpr auto operator--() -> i32& {
--value;
return *this;
}
constexpr auto operator--(int) -> i32 {
i32 tmp(*this);
--(*this);
return tmp;
}
constexpr auto operator~() const -> i32 {
return i32(~value);
}
constexpr operator int32_t() const {
return value;
}
int32_t value;
};
Код: Выделить всё
u64 a = 10; // u64 is a uint64_t replacement
i32 b = static_cast(a); // argument: conversion from uint64_t to int32_t, possible loss of data.
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/78717916/custom-integer-like-datatype-with-support-for-static-casts-without-warnings[/url]