Any type.

master
Nicole Collings 2020-03-23 22:40:19 -07:00
parent 2baf847828
commit 3ed1aad854
2 changed files with 50 additions and 1 deletions

View File

@ -14,7 +14,14 @@
#pragma clang diagnostic pop
#include "StartGame.h"
#include "util/Any.h"
int main(int argc, char* argv[]) {
return StartGame(argc, argv);
// return StartGame(argc, argv);
Any a(new std::string("whee"));
Any b(new int(125));
std::cout << *a.get<std::string>() << std::endl;
std::cout << *b.get<int>() << std::endl;
}

42
src/util/Any.h Normal file
View File

@ -0,0 +1,42 @@
//
// Created by aurailus on 2020-03-23.
//
#pragma once
#include <typeinfo>
class Any {
public:
Any() = default;
template <typename T> Any(T* val) {
set<T>(val);
}
template <typename T> void set(T* 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);
}
bool empty() {
return !hasData;
}
template <typename T> void erase() {
if (!hasData) return;
hasData = false;
delete static_cast<T*>(data);
type = 0;
}
private:
std::size_t type = 0;
bool hasData = false;
void* data = nullptr;
};