Merge bitcoin/bitcoin#31904: refactor: modernize outdated trait patterns using helper aliases (C++14/C++17)

4cd95a2921 refactor: modernize remaining outdated trait patterns (Lőrinc)
ab2b67fce2 scripted-diff: modernize outdated trait patterns - values (Lőrinc)
8327889f35 scripted-diff: modernize outdated trait patterns - types (Lőrinc)

Pull request description:

  The use of [`std::underlying_type_t<T>`](https://en.cppreference.com/w/cpp/types/underlying_type) or [`std::is_enum_v<T>`](https://en.cppreference.com/w/cpp/types/is_enum) (and similar ones, introduced in C++14) replace the `typename std::underlying_type<T>::type` and  `std::is_enum<T>::value` constructs (available in C++11).

  The `_t` and `_v` helper alias templates offer a more concise way to extract the type and value directly.

  I've modified the instances I found in the codebase one-by-one (noticed them while investigating https://github.com/bitcoin/bitcoin/pull/31868), and afterwards extracted scripted diff commits to do the trivial ones automatically.
  The last commit contains the values that were easier done manually.

  I've excluded changes from `src/bench/nanobench.h`, `src/leveldb`, `src/minisketch`, `src/span.h` and `src/sync.h` - let me know if you think they should be included instead.

  A few of the code changes can also be reproduced by clang-tidy (but not all of them):
  ```bash
  cmake -B build -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DBUILD_BENCH=ON -DBUILD_FUZZ_BINARY=ON -DBUILD_FOR_FUZZING=ON && cmake --build build -j$(nproc)
  run-clang-tidy -quiet -p build -j $(nproc) -checks='-*,modernize-type-traits' -fix $(git grep -lE '::(value|type)' ./src ':(exclude)src/bench/nanobench.h' ':(exclude)src/leveldb' ':(exclude)src/minisketch' ':(exclude)src/span.h' ':(exclude)src/sync.h')
  ```

ACKs for top commit:
  laanwj:
    Concept and code review ACK 4cd95a2921

Tree-SHA512: a4bcf0f267c0f4e02983b4d548ed6f58d464ec379ac5cd1f998b9ec0cf698b53a9f2557a05a342b661f1d94adefc9a0ce2dc8f764d49453aaea95451e2c4c581
This commit is contained in:
merge-script 2025-03-17 13:10:10 +08:00
commit a799415d84
No known key found for this signature in database
GPG key ID: 2EEB9F5CC09526C1
21 changed files with 47 additions and 47 deletions

View file

@ -16,11 +16,11 @@ struct nontrivial_t {
nontrivial_t() = default; nontrivial_t() = default;
SERIALIZE_METHODS(nontrivial_t, obj) { READWRITE(obj.x); } SERIALIZE_METHODS(nontrivial_t, obj) { READWRITE(obj.x); }
}; };
static_assert(!std::is_trivially_default_constructible<nontrivial_t>::value, static_assert(!std::is_trivially_default_constructible_v<nontrivial_t>,
"expected nontrivial_t to not be trivially constructible"); "expected nontrivial_t to not be trivially constructible");
typedef unsigned char trivial_t; typedef unsigned char trivial_t;
static_assert(std::is_trivially_default_constructible<trivial_t>::value, static_assert(std::is_trivially_default_constructible_v<trivial_t>,
"expected trivial_t to be trivially constructible"); "expected trivial_t to be trivially constructible");
template <typename T> template <typename T>

View file

@ -24,7 +24,7 @@ static_assert(!ValidDeployment(static_cast<Consensus::BuriedDeployment>(Consensu
template<typename T, T x> template<typename T, T x>
static constexpr bool is_minimum() static constexpr bool is_minimum()
{ {
using U = typename std::underlying_type<T>::type; using U = std::underlying_type_t<T>;
return x == std::numeric_limits<U>::min(); return x == std::numeric_limits<U>::min();
} }

View file

@ -45,7 +45,7 @@ enum class AddressPurpose;
enum isminetype : unsigned int; enum isminetype : unsigned int;
struct CRecipient; struct CRecipient;
struct WalletContext; struct WalletContext;
using isminefilter = std::underlying_type<isminetype>::type; using isminefilter = std::underlying_type_t<isminetype>;
} // namespace wallet } // namespace wallet
namespace interfaces { namespace interfaces {

View file

@ -67,11 +67,11 @@ public:
} }
const auto duration{end_time - *m_start_t}; const auto duration{end_time - *m_start_t};
if constexpr (std::is_same<TimeType, std::chrono::microseconds>::value) { if constexpr (std::is_same_v<TimeType, std::chrono::microseconds>) {
return strprintf("%s: %s (%iμs)", m_prefix, msg, Ticks<std::chrono::microseconds>(duration)); return strprintf("%s: %s (%iμs)", m_prefix, msg, Ticks<std::chrono::microseconds>(duration));
} else if constexpr (std::is_same<TimeType, std::chrono::milliseconds>::value) { } else if constexpr (std::is_same_v<TimeType, std::chrono::milliseconds>) {
return strprintf("%s: %s (%.2fms)", m_prefix, msg, Ticks<MillisecondsDouble>(duration)); return strprintf("%s: %s (%.2fms)", m_prefix, msg, Ticks<MillisecondsDouble>(duration));
} else if constexpr (std::is_same<TimeType, std::chrono::seconds>::value) { } else if constexpr (std::is_same_v<TimeType, std::chrono::seconds>) {
return strprintf("%s: %s (%.2fs)", m_prefix, msg, Ticks<SecondsDouble>(duration)); return strprintf("%s: %s (%.2fs)", m_prefix, msg, Ticks<SecondsDouble>(duration));
} else { } else {
static_assert(ALWAYS_FALSE<TimeType>, "Error: unexpected time type"); static_assert(ALWAYS_FALSE<TimeType>, "Error: unexpected time type");

View file

@ -48,7 +48,7 @@ enum class NetPermissionFlags : uint32_t {
}; };
static inline constexpr NetPermissionFlags operator|(NetPermissionFlags a, NetPermissionFlags b) static inline constexpr NetPermissionFlags operator|(NetPermissionFlags a, NetPermissionFlags b)
{ {
using t = typename std::underlying_type<NetPermissionFlags>::type; using t = std::underlying_type_t<NetPermissionFlags>;
return static_cast<NetPermissionFlags>(static_cast<t>(a) | static_cast<t>(b)); return static_cast<NetPermissionFlags>(static_cast<t>(a) | static_cast<t>(b));
} }
@ -59,7 +59,7 @@ public:
static std::vector<std::string> ToStrings(NetPermissionFlags flags); static std::vector<std::string> ToStrings(NetPermissionFlags flags);
static inline bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f) static inline bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
{ {
using t = typename std::underlying_type<NetPermissionFlags>::type; using t = std::underlying_type_t<NetPermissionFlags>;
return (static_cast<t>(flags) & static_cast<t>(f)) == static_cast<t>(f); return (static_cast<t>(flags) & static_cast<t>(f)) == static_cast<t>(f);
} }
static inline void AddFlag(NetPermissionFlags& flags, NetPermissionFlags f) static inline void AddFlag(NetPermissionFlags& flags, NetPermissionFlags f)
@ -74,7 +74,7 @@ public:
static inline void ClearFlag(NetPermissionFlags& flags, NetPermissionFlags f) static inline void ClearFlag(NetPermissionFlags& flags, NetPermissionFlags f)
{ {
assert(f == NetPermissionFlags::Implicit); assert(f == NetPermissionFlags::Implicit);
using t = typename std::underlying_type<NetPermissionFlags>::type; using t = std::underlying_type_t<NetPermissionFlags>;
flags = static_cast<NetPermissionFlags>(static_cast<t>(flags) & ~static_cast<t>(f)); flags = static_cast<NetPermissionFlags>(static_cast<t>(flags) & ~static_cast<t>(f));
} }
}; };

View file

@ -37,12 +37,12 @@ enum class ConnectionDirection {
Both = (In | Out), Both = (In | Out),
}; };
static inline ConnectionDirection& operator|=(ConnectionDirection& a, ConnectionDirection b) { static inline ConnectionDirection& operator|=(ConnectionDirection& a, ConnectionDirection b) {
using underlying = typename std::underlying_type<ConnectionDirection>::type; using underlying = std::underlying_type_t<ConnectionDirection>;
a = ConnectionDirection(underlying(a) | underlying(b)); a = ConnectionDirection(underlying(a) | underlying(b));
return a; return a;
} }
static inline bool operator&(ConnectionDirection a, ConnectionDirection b) { static inline bool operator&(ConnectionDirection a, ConnectionDirection b) {
using underlying = typename std::underlying_type<ConnectionDirection>::type; using underlying = std::underlying_type_t<ConnectionDirection>;
return (underlying(a) & underlying(b)); return (underlying(a) & underlying(b));
} }

View file

@ -334,7 +334,7 @@ public:
/** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */ /** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */
template <StdChronoDuration Dur> template <StdChronoDuration Dur>
Dur randrange(typename std::common_type_t<Dur> range) noexcept Dur randrange(std::common_type_t<Dur> range) noexcept
// Having the compiler infer the template argument from the function argument // Having the compiler infer the template argument from the function argument
// is dangerous, because the desired return value generally has a different // is dangerous, because the desired return value generally has a different
// type than the function argument. So std::common_type is used to force the // type than the function argument. So std::common_type is used to force the

View file

@ -70,10 +70,10 @@ namespace {
*/ */
template<typename T> template<typename T>
CSHA512& operator<<(CSHA512& hasher, const T& data) { CSHA512& operator<<(CSHA512& hasher, const T& data) {
static_assert(!std::is_same<typename std::decay<T>::type, char*>::value, "Calling operator<<(CSHA512, char*) is probably not what you want"); static_assert(!std::is_same_v<std::decay_t<T>, char*>, "Calling operator<<(CSHA512, char*) is probably not what you want");
static_assert(!std::is_same<typename std::decay<T>::type, unsigned char*>::value, "Calling operator<<(CSHA512, unsigned char*) is probably not what you want"); static_assert(!std::is_same_v<std::decay_t<T>, unsigned char*>, "Calling operator<<(CSHA512, unsigned char*) is probably not what you want");
static_assert(!std::is_same<typename std::decay<T>::type, const char*>::value, "Calling operator<<(CSHA512, const char*) is probably not what you want"); static_assert(!std::is_same_v<std::decay_t<T>, const char*>, "Calling operator<<(CSHA512, const char*) is probably not what you want");
static_assert(!std::is_same<typename std::decay<T>::type, const unsigned char*>::value, "Calling operator<<(CSHA512, const unsigned char*) is probably not what you want"); static_assert(!std::is_same_v<std::decay_t<T>, const unsigned char*>, "Calling operator<<(CSHA512, const unsigned char*) is probably not what you want");
hasher.Write((const unsigned char*)&data, sizeof(data)); hasher.Write((const unsigned char*)&data, sizeof(data));
return hasher; return hasher;
} }

View file

@ -49,7 +49,7 @@ const std::string EXAMPLE_ADDRESS[2] = {"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hu
std::string GetAllOutputTypes() std::string GetAllOutputTypes()
{ {
std::vector<std::string> ret; std::vector<std::string> ret;
using U = std::underlying_type<TxoutType>::type; using U = std::underlying_type_t<TxoutType>;
for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) { for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) {
ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i))); ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
} }

View file

@ -154,7 +154,7 @@ const Out& AsBase(const In& x)
} }
#define READWRITE(...) (ser_action.SerReadWriteMany(s, __VA_ARGS__)) #define READWRITE(...) (ser_action.SerReadWriteMany(s, __VA_ARGS__))
#define SER_READ(obj, code) ser_action.SerRead(s, obj, [&](Stream& s, typename std::remove_const<Type>::type& obj) { code; }) #define SER_READ(obj, code) ser_action.SerRead(s, obj, [&](Stream& s, std::remove_const_t<Type>& obj) { code; })
#define SER_WRITE(obj, code) ser_action.SerWrite(s, obj, [&](Stream& s, const Type& obj) { code; }) #define SER_WRITE(obj, code) ser_action.SerWrite(s, obj, [&](Stream& s, const Type& obj) { code; })
/** /**
@ -220,13 +220,13 @@ const Out& AsBase(const In& x)
template <typename Stream> \ template <typename Stream> \
void Serialize(Stream& s) const \ void Serialize(Stream& s) const \
{ \ { \
static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \ static_assert(std::is_same_v<const cls&, decltype(*this)>, "Serialize type mismatch"); \
Ser(s, *this); \ Ser(s, *this); \
} \ } \
template <typename Stream> \ template <typename Stream> \
void Unserialize(Stream& s) \ void Unserialize(Stream& s) \
{ \ { \
static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch"); \ static_assert(std::is_same_v<cls&, decltype(*this)>, "Unserialize type mismatch"); \
Unser(s, *this); \ Unser(s, *this); \
} }
@ -408,8 +408,8 @@ template <VarIntMode Mode, typename I>
struct CheckVarIntMode { struct CheckVarIntMode {
constexpr CheckVarIntMode() constexpr CheckVarIntMode()
{ {
static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned<I>::value, "Unsigned type required with mode DEFAULT."); static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned_v<I>, "Unsigned type required with mode DEFAULT.");
static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed<I>::value, "Signed type required with mode NONNEGATIVE_SIGNED."); static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed_v<I>, "Signed type required with mode NONNEGATIVE_SIGNED.");
} }
}; };
@ -474,7 +474,7 @@ I ReadVarInt(Stream& is)
template<typename Formatter, typename T> template<typename Formatter, typename T>
class Wrapper class Wrapper
{ {
static_assert(std::is_lvalue_reference<T>::value, "Wrapper needs an lvalue reference type T"); static_assert(std::is_lvalue_reference_v<T>, "Wrapper needs an lvalue reference type T");
protected: protected:
T m_object; T m_object;
public: public:
@ -507,12 +507,12 @@ struct VarIntFormatter
{ {
template<typename Stream, typename I> void Ser(Stream &s, I v) template<typename Stream, typename I> void Ser(Stream &s, I v)
{ {
WriteVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s, v); WriteVarInt<Stream,Mode, std::remove_cv_t<I>>(s, v);
} }
template<typename Stream, typename I> void Unser(Stream& s, I& v) template<typename Stream, typename I> void Unser(Stream& s, I& v)
{ {
v = ReadVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s); v = ReadVarInt<Stream,Mode, std::remove_cv_t<I>>(s);
} }
}; };
@ -545,7 +545,7 @@ struct CustomUintFormatter
template <typename Stream, typename I> void Unser(Stream& s, I& v) template <typename Stream, typename I> void Unser(Stream& s, I& v)
{ {
using U = typename std::conditional<std::is_enum<I>::value, std::underlying_type<I>, std::common_type<I>>::type::type; using U = typename std::conditional_t<std::is_enum_v<I>, std::underlying_type<I>, std::common_type<I>>::type;
static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0, "Assigned type too small"); static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0, "Assigned type too small");
uint64_t raw = 0; uint64_t raw = 0;
if (BigEndian) { if (BigEndian) {
@ -577,7 +577,7 @@ struct CompactSizeFormatter
template<typename Stream, typename I> template<typename Stream, typename I>
void Ser(Stream& s, I v) void Ser(Stream& s, I v)
{ {
static_assert(std::is_unsigned<I>::value, "CompactSize only supported for unsigned integers"); static_assert(std::is_unsigned_v<I>, "CompactSize only supported for unsigned integers");
static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below"); static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below");
WriteCompactSize<Stream>(s, v); WriteCompactSize<Stream>(s, v);

View file

@ -148,8 +148,8 @@ template <typename MutexType>
static void push_lock(MutexType* c, const CLockLocation& locklocation) static void push_lock(MutexType* c, const CLockLocation& locklocation)
{ {
constexpr bool is_recursive_mutex = constexpr bool is_recursive_mutex =
std::is_base_of<RecursiveMutex, MutexType>::value || std::is_base_of_v<RecursiveMutex, MutexType> ||
std::is_base_of<std::recursive_mutex, MutexType>::value; std::is_base_of_v<std::recursive_mutex, MutexType>;
LockData& lockdata = GetLockData(); LockData& lockdata = GetLockData();
std::lock_guard<std::mutex> lock(lockdata.dd_mutex); std::lock_guard<std::mutex> lock(lockdata.dd_mutex);

View file

@ -203,7 +203,7 @@ template <typename T> T FuzzedDataProvider::ConsumeIntegral() {
// be less than or equal to |max|. // be less than or equal to |max|.
template <typename T> template <typename T>
T FuzzedDataProvider::ConsumeIntegralInRange(T min, T max) { T FuzzedDataProvider::ConsumeIntegralInRange(T min, T max) {
static_assert(std::is_integral<T>::value, "An integral type is required."); static_assert(std::is_integral_v<T>, "An integral type is required.");
static_assert(sizeof(T) <= sizeof(uint64_t), "Unsupported integral type."); static_assert(sizeof(T) <= sizeof(uint64_t), "Unsupported integral type.");
if (min > max) if (min > max)
@ -271,14 +271,14 @@ T FuzzedDataProvider::ConsumeFloatingPointInRange(T min, T max) {
// Returns a floating point number in the range [0.0, 1.0]. If there's no // Returns a floating point number in the range [0.0, 1.0]. If there's no
// input data left, always returns 0. // input data left, always returns 0.
template <typename T> T FuzzedDataProvider::ConsumeProbability() { template <typename T> T FuzzedDataProvider::ConsumeProbability() {
static_assert(std::is_floating_point<T>::value, static_assert(std::is_floating_point_v<T>,
"A floating point type is required."); "A floating point type is required.");
// Use different integral types for different floating point types in order // Use different integral types for different floating point types in order
// to provide better density of the resulting values. // to provide better density of the resulting values.
using IntegralType = using IntegralType =
typename std::conditional<(sizeof(T) <= sizeof(uint32_t)), uint32_t, typename std::conditional_t<(sizeof(T) <= sizeof(uint32_t)), uint32_t,
uint64_t>::type; uint64_t>;
T result = static_cast<T>(ConsumeIntegral<IntegralType>()); T result = static_cast<T>(ConsumeIntegral<IntegralType>());
result /= static_cast<T>(std::numeric_limits<IntegralType>::max()); result /= static_cast<T>(std::numeric_limits<IntegralType>::max());
@ -294,7 +294,7 @@ inline bool FuzzedDataProvider::ConsumeBool() {
// also contain |kMaxValue| aliased to its largest (inclusive) value. Such as: // also contain |kMaxValue| aliased to its largest (inclusive) value. Such as:
// enum class Foo { SomeValue, OtherValue, kMaxValue = OtherValue }; // enum class Foo { SomeValue, OtherValue, kMaxValue = OtherValue };
template <typename T> T FuzzedDataProvider::ConsumeEnum() { template <typename T> T FuzzedDataProvider::ConsumeEnum() {
static_assert(std::is_enum<T>::value, "|T| must be an enum type."); static_assert(std::is_enum_v<T>, "|T| must be an enum type.");
return static_cast<T>( return static_cast<T>(
ConsumeIntegralInRange<uint32_t>(0, static_cast<uint32_t>(T::kMaxValue))); ConsumeIntegralInRange<uint32_t>(0, static_cast<uint32_t>(T::kMaxValue)));
} }

View file

@ -63,7 +63,7 @@ FUZZ_TARGET(integer, .init = initialize_integer)
const int16_t i16 = fuzzed_data_provider.ConsumeIntegral<int16_t>(); const int16_t i16 = fuzzed_data_provider.ConsumeIntegral<int16_t>();
const uint8_t u8 = fuzzed_data_provider.ConsumeIntegral<uint8_t>(); const uint8_t u8 = fuzzed_data_provider.ConsumeIntegral<uint8_t>();
const int8_t i8 = fuzzed_data_provider.ConsumeIntegral<int8_t>(); const int8_t i8 = fuzzed_data_provider.ConsumeIntegral<int8_t>();
// We cannot assume a specific value of std::is_signed<char>::value: // We cannot assume a specific value of std::is_signed_v<char>:
// ConsumeIntegral<char>() instead of casting from {u,}int8_t. // ConsumeIntegral<char>() instead of casting from {u,}int8_t.
const char ch = fuzzed_data_provider.ConsumeIntegral<char>(); const char ch = fuzzed_data_provider.ConsumeIntegral<char>();
const bool b = fuzzed_data_provider.ConsumeBool(); const bool b = fuzzed_data_provider.ConsumeBool();

View file

@ -134,7 +134,7 @@ template <typename WeakEnumType, size_t size>
{ {
return fuzzed_data_provider.ConsumeBool() ? return fuzzed_data_provider.ConsumeBool() ?
fuzzed_data_provider.PickValueInArray<WeakEnumType>(all_types) : fuzzed_data_provider.PickValueInArray<WeakEnumType>(all_types) :
WeakEnumType(fuzzed_data_provider.ConsumeIntegral<typename std::underlying_type<WeakEnumType>::type>()); WeakEnumType(fuzzed_data_provider.ConsumeIntegral<std::underlying_type_t<WeakEnumType>>());
} }
[[nodiscard]] inline opcodetype ConsumeOpcodeType(FuzzedDataProvider& fuzzed_data_provider) noexcept [[nodiscard]] inline opcodetype ConsumeOpcodeType(FuzzedDataProvider& fuzzed_data_provider) noexcept
@ -207,7 +207,7 @@ template <typename WeakEnumType, size_t size>
template <typename T> template <typename T>
[[nodiscard]] bool MultiplicationOverflow(const T i, const T j) noexcept [[nodiscard]] bool MultiplicationOverflow(const T i, const T j) noexcept
{ {
static_assert(std::is_integral<T>::value, "Integral required."); static_assert(std::is_integral_v<T>, "Integral required.");
if (std::numeric_limits<T>::is_signed) { if (std::numeric_limits<T>::is_signed) {
if (i > 0) { if (i > 0) {
if (j > 0) { if (j > 0) {

View file

@ -137,7 +137,7 @@ void UniValue::push_backV(It first, It last)
template <typename Int> template <typename Int>
Int UniValue::getInt() const Int UniValue::getInt() const
{ {
static_assert(std::is_integral<Int>::value); static_assert(std::is_integral_v<Int>);
checkType(VNUM); checkType(VNUM);
Int result; Int result;
const auto [first_nonmatching, error_condition] = std::from_chars(val.data(), val.data() + val.size(), result); const auto [first_nonmatching, error_condition] = std::from_chars(val.data(), val.data() + val.size(), result);

View file

@ -163,7 +163,7 @@ static inline std::string PathToString(const path& path)
#ifdef WIN32 #ifdef WIN32
return path.utf8string(); return path.utf8string();
#else #else
static_assert(std::is_same<path::string_type, std::string>::value, "PathToString not implemented on this platform"); static_assert(std::is_same_v<path::string_type, std::string>, "PathToString not implemented on this platform");
return path.std::filesystem::path::string(); return path.std::filesystem::path::string();
#endif #endif
} }

View file

@ -14,7 +14,7 @@
template <class T> template <class T>
[[nodiscard]] bool AdditionOverflow(const T i, const T j) noexcept [[nodiscard]] bool AdditionOverflow(const T i, const T j) noexcept
{ {
static_assert(std::is_integral<T>::value, "Integral required."); static_assert(std::is_integral_v<T>, "Integral required.");
if constexpr (std::numeric_limits<T>::is_signed) { if constexpr (std::numeric_limits<T>::is_signed) {
return (i > 0 && j > std::numeric_limits<T>::max() - i) || return (i > 0 && j > std::numeric_limits<T>::max() - i) ||
(i < 0 && j < std::numeric_limits<T>::min() - i); (i < 0 && j < std::numeric_limits<T>::min() - i);

View file

@ -204,7 +204,7 @@ namespace {
template <typename T> template <typename T>
bool ParseIntegral(std::string_view str, T* out) bool ParseIntegral(std::string_view str, T* out)
{ {
static_assert(std::is_integral<T>::value); static_assert(std::is_integral_v<T>);
// Replicate the exact behavior of strtol/strtoll/strtoul/strtoull when // Replicate the exact behavior of strtol/strtoll/strtoul/strtoull when
// handling leading +/- for backwards compatibility. // handling leading +/- for backwards compatibility.
if (str.length() >= 2 && str[0] == '+' && str[1] == '-') { if (str.length() >= 2 && str[0] == '+' && str[1] == '-') {

View file

@ -117,7 +117,7 @@ bool SplitHostPort(std::string_view in, uint16_t& portOut, std::string& hostOut)
template <typename T> template <typename T>
T LocaleIndependentAtoi(std::string_view str) T LocaleIndependentAtoi(std::string_view str)
{ {
static_assert(std::is_integral<T>::value); static_assert(std::is_integral_v<T>);
T result; T result;
// Emulate atoi(...) handling of white space and leading +/-. // Emulate atoi(...) handling of white space and leading +/-.
std::string_view s = util::TrimStringView(str); std::string_view s = util::TrimStringView(str);
@ -178,7 +178,7 @@ constexpr inline bool IsSpace(char c) noexcept {
template <typename T> template <typename T>
std::optional<T> ToIntegral(std::string_view str) std::optional<T> ToIntegral(std::string_view str)
{ {
static_assert(std::is_integral<T>::value); static_assert(std::is_integral_v<T>);
T result; T result;
const auto [first_nonmatching, error_condition] = std::from_chars(str.data(), str.data() + str.size(), result); const auto [first_nonmatching, error_condition] = std::from_chars(str.data(), str.data() + str.size(), result);
if (first_nonmatching != str.data() + str.size() || error_condition != std::errc{}) { if (first_nonmatching != str.data() + str.size() || error_condition != std::errc{}) {

View file

@ -20,9 +20,9 @@
* (list initialization always copies). * (list initialization always copies).
*/ */
template<typename... Args> template<typename... Args>
inline std::vector<typename std::common_type<Args...>::type> Vector(Args&&... args) inline std::vector<std::common_type_t<Args...>> Vector(Args&&... args)
{ {
std::vector<typename std::common_type<Args...>::type> ret; std::vector<std::common_type_t<Args...>> ret;
ret.reserve(sizeof...(args)); ret.reserve(sizeof...(args));
// The line below uses the trick from https://www.experts-exchange.com/articles/32502/None-recursive-variadic-templates-with-std-initializer-list.html // The line below uses the trick from https://www.experts-exchange.com/articles/32502/None-recursive-variadic-templates-with-std-initializer-list.html
(void)std::initializer_list<int>{(ret.emplace_back(std::forward<Args>(args)), 0)...}; (void)std::initializer_list<int>{(ret.emplace_back(std::forward<Args>(args)), 0)...};

View file

@ -48,7 +48,7 @@ enum isminetype : unsigned int {
ISMINE_ENUM_ELEMENTS, ISMINE_ENUM_ELEMENTS,
}; };
/** used for bitflags of isminetype */ /** used for bitflags of isminetype */
using isminefilter = std::underlying_type<isminetype>::type; using isminefilter = std::underlying_type_t<isminetype>;
/** /**
* Address purpose field that has been been stored with wallet sending and * Address purpose field that has been been stored with wallet sending and