-
-
Save dloman/5f8334d0163e4d4273682175dc6bfa74 to your computer and use it in GitHub Desktop.
simple any implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <memory> | |
#include <typeinfo> | |
struct bad_any_cast | |
{ | |
}; | |
class any | |
{ | |
private: | |
struct base | |
{ | |
virtual ~base() = default; | |
virtual const std::type_info& get_type() = 0; | |
}; | |
template<typename T> | |
struct child : public base | |
{ | |
child(T t) | |
: mT(t) | |
{ | |
} | |
const std::type_info& get_type() override | |
{ | |
return typeid(T); | |
} | |
T mT; | |
}; | |
std::unique_ptr<base> mpBase; | |
public: | |
any() | |
: mpBase(nullptr) | |
{ | |
} | |
template <typename T> | |
any(T t) | |
: mpBase(std::make_unique<child<T>>(t)) | |
{ | |
} | |
template <typename T> | |
T any_cast() | |
{ | |
if (!mpBase || typeid(T) != get_type()) | |
{ | |
throw bad_any_cast{}; | |
} | |
return static_cast<child<T>*> (mpBase.get())->mT; | |
} | |
const std::type_info& get_type() const | |
{ | |
if (!mpBase) | |
{ | |
return typeid(nullptr); | |
} | |
return mpBase->get_type(); | |
} | |
}; | |
int main() | |
{ | |
any a; | |
a = 5; | |
std::cout << a.any_cast<int>() << std::endl; | |
a = "works"; | |
std::cout << a.any_cast<const char*>() << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment