Improved Any type.

master
Nicole Collings 2020-03-24 12:00:23 -07:00
parent 3ed1aad854
commit 9a46f2077d
4 changed files with 42 additions and 21 deletions

View File

@ -1,4 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DiscordIntegrationProjectSettings" description="Multiplayer Voxel Game" />
<component name="DiscordProjectSettings">
<option name="show" value="true" />
</component>
<component name="ProjectNotificationSettings">
<option name="askShowProject" value="false" />
</component>
</project>

View File

@ -19,9 +19,9 @@
int main(int argc, char* argv[]) {
// return StartGame(argc, argv);
Any a(new std::string("whee"));
Any b(new int(125));
auto a = Any::from<std::string>({"wee"});
auto b = Any(a);
b.set<int>(57);
std::cout << *a.get<std::string>() << std::endl;
std::cout << *b.get<int>() << std::endl;
std::cout << a.get<std::string>() << ", " << b.get_or<std::string>("fuck that") << std::endl;
}

View File

@ -9,34 +9,43 @@
class Any {
public:
Any() = default;
template <typename T> Any(T* val) {
set<T>(val);
template <typename T> static Any from(const T& val) {
Any a;
a.set<T>(val);
return a;
}
template <typename T> void set(T* val) {
template <typename T> void set(const T& val) noexcept {
data = std::make_shared<T>(std::move(val));
type = typeid(T).hash_code();
hasData = true;
data = val;
}
template <typename T> T* get() {
if (!hasData || type != typeid(T).hash_code()) return nullptr;
return static_cast<T*>(data);
template<typename T> const T& get() const {
if (empty()) throw std::logic_error("Tried to get empty Any.");
else if (type != typeid(T).hash_code()) throw std::logic_error("Any is not of type specified.");
return *std::static_pointer_cast<T>(data);
}
bool empty() {
return !hasData;
template<typename T> const T& get_or(const T& other) const noexcept {
try { return get<T>(); }
catch (...) { return other; }
}
template <typename T> void erase() {
if (!hasData) return;
hasData = false;
delete static_cast<T*>(data);
template <typename T> const bool is() const noexcept {
return typeid(T).hash_code() == type;
}
bool const empty() const noexcept {
return !data;
}
void reset() noexcept {
data = nullptr;
type = 0;
}
private:
std::size_t type = 0;
bool hasData = false;
void* data = nullptr;
std::shared_ptr<void> data = nullptr;
};

View File

@ -31,9 +31,15 @@ namespace Util {
return floatToString((float)val);
}
static std::string vecToString(glm::ivec3 vec) {
std::ostringstream out;
out << vec.x << ", " << vec.y << ", " << vec.z;
return out.str();
}
static std::string vecToString(glm::vec3 vec) {
std::ostringstream out;
out << (int)vec.x << ", " << (int)vec.y << ", " << (int)vec.z;
out << vec.x << ", " << vec.y << ", " << vec.z;
return out.str();
}