Skip to content

Instantly share code, notes, and snippets.

@takiyu
Last active April 19, 2018 04:14
Show Gist options
  • Save takiyu/f5dac4b1608324345053b07e708de092 to your computer and use it in GitHub Desktop.
Save takiyu/f5dac4b1608324345053b07e708de092 to your computer and use it in GitHub Desktop.
Variable class for wrapping any type variables like as a typess language.
#include <iostream>
#include <vector>
#include <memory>
#include <typeinfo>
#include <cstring>
class Variable {
public:
template<typename T, typename... Args>
void create(Args... args) {
set(std::make_shared<T>(args...));
}
template<typename T>
void set(std::shared_ptr<T> v) {
data = v;
type = &typeid(T); // The lifetime extends to the end of the program.
}
template<typename T>
std::shared_ptr<T> get() {
if (*type != typeid(T)) {
std::cerr << "Invalid cast (" << type->name() << " vs "
<< typeid(T).name() << ")" << std::endl;
return std::make_shared<T>();
}
return std::static_pointer_cast<T>(data);
}
private:
std::shared_ptr<void> data;
const std::type_info *type = &typeid(void);
};
int main(int argc, char const* argv[]) {
// Create with variable creation
Variable v1, v2, v3;
v1.create<std::vector<float>>(10);
v2.create<float>(123);
// Create with setting outer variable
std::shared_ptr<int> int_ptr = std::make_shared<int>(456);
v3.set(int_ptr);
// Correct cast
std::cout << v1.get<std::vector<float>>()->size() << std::endl;
std::cout << *(v2.get<float>()) << std::endl;
std::cout << *(v3.get<int>()) << std::endl;
// Incorrect cast
std::cout << *(v1.get<float>()) << std::endl;
std::cout << *(v2.get<int>()) << std::endl;
std::cout << v3.get<std::vector<float>>()->size() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment