feat Add Any
All checks were successful
linux-x64-gcc / linux-gcc (Release) (push) Successful in 57s
linux-x64-gcc / linux-gcc (Debug) (push) Successful in 10m3s

This commit is contained in:
tqcq 2024-03-13 21:19:34 +08:00
parent f8d2b051ee
commit 2df2fcb687
3 changed files with 91 additions and 0 deletions

View File

@ -99,6 +99,7 @@ if(SLED_BUILD_TESTS)
) )
FetchContent_MakeAvailable(googletest) FetchContent_MakeAvailable(googletest)
add_executable(sled_tests add_executable(sled_tests
src/any_test.cc
src/filesystem/path_test.cc src/filesystem/path_test.cc
src/strings/base64_test.cc src/strings/base64_test.cc
src/cleanup_test.cc src/cleanup_test.cc

View File

@ -332,6 +332,92 @@ any_cast(any &&operand)
return any_cast<ValueType>(operand); return any_cast<ValueType>(operand);
} }
class Any final {
public:
inline Any() {}
inline Any(const Any &other) : value_(other.value_) {}
inline Any(Any &&other) noexcept : value_(std::move(other.value_)) {}
template<typename ValueType>
inline Any(const ValueType &value) : value_(value)
{}
template<typename ValueType>
inline Any(ValueType &&value) : value_(std::move(value))
{}
// ~Any() noexcept {}
Any &operator=(const Any &rhs)
{
Any(rhs).swap(*this);
return *this;
}
Any &operator=(Any &&rhs) noexcept
{
rhs.swap(*this);
Any().swap(rhs);
return *this;
}
template<typename ValueType>
Any &operator=(ValueType &&rhs)
{
Any(static_cast<ValueType &&>(rhs)).swap(*this);
return *this;
}
template<typename ValueType>
inline auto Cast() const -> ValueType
{
return any_cast<ValueType>(value_);
}
template<typename ValueType>
inline auto Cast() -> ValueType
{
return any_cast<ValueType>(value_);
}
template<typename ValueType, typename U = ValueType>
inline auto CastOr(U &&default_value) const -> ValueType
{
try {
return any_cast<ValueType>(value_);
} catch (const bad_any_cast &e) {
return static_cast<ValueType>(default_value);
}
}
template<typename ValueType, typename U = ValueType>
inline auto CastOr(U &&default_value) -> ValueType
{
try {
return any_cast<ValueType>(value_);
} catch (const bad_any_cast &e) {
return static_cast<ValueType>(default_value);
}
}
void Reset() noexcept { Any().swap(*this); }
bool HasValue() const noexcept { return value_.has_value(); }
const std::type_info &Type() const noexcept { return value_.type(); }
Any &swap(Any &rhs) noexcept
{
std::swap(value_, rhs.value_);
return *this;
}
private:
any value_;
};
}// namespace sled }// namespace sled
#endif /* SLED_ANY_H */ #endif /* SLED_ANY_H */

4
src/any_test.cc Normal file
View File

@ -0,0 +1,4 @@
#include <gtest/gtest.h>
#include <sled/any.h>
TEST(Any, Assign) {}