R-Type  2
Doom but in better
Loading...
Searching...
No Matches
UnCast.hpp
Go to the documentation of this file.
1/*
2** EPITECH PROJECT, 2024
3** rtype (Workspace)
4** File description:
5** unCast.hpp
6*/
7
8#pragma once
9
10#include <any>
11#include <string>
12#include <optional>
13#include <type_traits>
14
15#include "Log.hpp"
16#include "LogMacros.hpp"
17#include "CustomExceptions.hpp"
18
19namespace Utilities
20{
64 template<typename T, typename Exception = CustomExceptions::InvalidType>
65 std::optional<T> unCast(const std::any &classNode, const bool raiseOnError = true, const std::string customErrorMessage = "")
66 {
67 PRETTY_DEBUG << "custom error message: '" << customErrorMessage << "'" << std::endl;
68 if (classNode.type() != typeid(T)) {
69 if (raiseOnError) {
70 std::string errMsg = "The type contained in std::any does not";
71 errMsg += " match the expected type, Custom error message: '";
72 errMsg += customErrorMessage;
73 errMsg += "'.";
74 throw Exception(errMsg);
75 } else {
76 PRETTY_WARNING << "The type contained in std::any does"
77 << " not match the expected type, Custom error message: '"
78 << customErrorMessage
79 << "'." << std::endl;
80 return std::nullopt;
81 }
82 }
83 if (!classNode.has_value()) {
84 if (raiseOnError) {
85 throw Exception(customErrorMessage + " : " + classNode.type().name());
86 } else {
87 PRETTY_WARNING << "There is no content in '"
88 << std::string(classNode.type().name())
89 << "' , Custom error message : '"
90 << customErrorMessage
91 << "'" << std::endl;
92 return std::nullopt;
93 }
94 }
95 try {
96 return std::optional(std::any_cast<T>(classNode));
97 }
98 catch (std::bad_any_cast &e) {
99 if (raiseOnError) {
100 throw Exception(customErrorMessage + std::string(e.what()));
101 } else {
102 PRETTY_WARNING << "Any cast failed, Custom error message: '"
103 << customErrorMessage
104 << "', system error: " << std::string(e.what())
105 << std::endl;
106 return std::nullopt;
107 }
108 }
109 };
110}
File in charge of containing the custom errors that are going to be used for custom description error...
Macro definitions for logging messages with varying levels of detail and formatting.
#define PRETTY_DEBUG
Debug log with details and colour.
#define PRETTY_WARNING
Warning log with details and colour.
This is the file in charge of containing the Log class (the one in charge of outputing info only when...
std::optional< T > unCast(const std::any &classNode, const bool raiseOnError=true, const std::string customErrorMessage="")
Casts the content of a std::any back to its original type.
Definition UnCast.hpp:65