Created
July 28, 2017 16:48
-
-
Save bit-hack/037444c48810038c27202f6fbab387f9 to your computer and use it in GitHub Desktop.
Example tagged type structure
This file contains hidden or 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
#ifndef TAGVAL_H__ | |
#define TAGVAL_T__ | |
#include <typeinfo> | |
struct tagval_t { | |
tagval_t(int v): type_(typeid(int)), int_(v) {} | |
tagval_t(float v): type_(typeid(float)), float_(v) {} | |
tagval_t(const char *v): type_(typeid(const char *)), cstr_(v) {} | |
template <typename type_t> | |
bool is_a() const { | |
return typeid(type_t) == type_; | |
} | |
template <typename type_t> | |
type_t &get() { | |
assert(is_a<type_t>()); | |
return int_; | |
} | |
template <typename type_t> | |
const type_t &get() const { | |
assert(is_a<type_t>()); | |
return int_; | |
} | |
protected: | |
union { | |
int int_; | |
float float_; | |
const char *cstr_; | |
}; | |
const std::type_info &type_; | |
}; | |
#endif // TAGVAL_H__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment