SafeCast is a C++ library that provides a safe way to cast between different integer types, preventing overflow and underflow errors. It's designed to be easy to use and integrate into existing projects, offering a lightweight alternative to boost::numeric_cast.
- Supports casting between signed and unsigned integers of different sizes.
- Header-only library.
- Throws exceptions for overflow and underflow conditions with useful exception messages.
- No external dependencies.
To use SafeCast in your project, simply copy the safe_cast.hpp
file into your project directory and include it in your source files.
#include "safe_cast.hpp"
// Safe casts that will succeed
auto const a = sc::safe_cast<int>(0ULL);
auto const b = sc::safe_cast<uint32_t>(int64_t{100});
auto const c = sc::safe_cast<int>(120ULL);
// Casts that will throw exceptions
try {
auto const d = sc::safe_cast<int8_t>(std::numeric_limits<int16_t>::min());
} catch (std::underflow_error const& ex) {
std::cerr << ex.what() << std::endl; // "Underflow casting from short (value: -32768) to signed char."
}
try {
auto const e = sc::safe_cast<uint32_t>(std::numeric_limits<int64_t>::max());
} catch (std::overflow_error const& ex) {
std::cerr << ex.what() << std::endl; // "Overflow casting from __int64 (value: 9223372036854775807) to unsigned int."
}
- C++ 20
This project is licensed under the MIT License - see the LICENSE file for details.
This project was inspired by the boost::numeric_cast library, which provides similar functionality for casting between numeric types. SafeCast is designed to be a lightweight alternative that is easier to integrate into existing projects.
- Richard Haar