I'm attempting to re-create the any that is found in Boost::any and I have built the three classes, however, whenever I come to reinterpret_cast for the value that is given, the output is completely different and just throws out garbage. Here is my code below:
namespace Types {
class PlaceMaker {
public:
PlaceMaker() { };
virtual ~PlaceMaker()
{
}
virtual PlaceMaker * clone()
{
return 0;
}
virtual const std::type_info & type() const = 0;
protected:
};
template<typename T>
class holder : public PlaceMaker {
public:
holder(const T & value)
: held(value)
{
}
virtual const std::type_info & type() const
{
return typeid(T);
}
virtual PlaceMaker * clone() const
{
return new holder(held);
}
T retrunHeld() const {
return held;
}
public:
T held;
//holder &operator=(const holder &) const = 0;
holder & operator=(const holder &) { }
};
class Any : PlaceMaker {
public:
Any() : maker(0) { };
template<typename ValueType>
Any(const ValueType & value)
: maker(new holder<ValueType>(value))
{
}
Any(const Any & other)
: maker(other.maker ? other.maker->clone() : 0)
{
}
Any& swap(Any &rhs) {
std::swap(maker, rhs.maker);
return *this;
}
template<typename ValueType>
Any & operator=(const ValueType & rhs)
{
Any(rhs).swap(*this);
return *this;
}
Any & operator=(Any rhs)
{
rhs.swap(*this);
return *this;
}
bool empty() const
{
return !maker;
}
const std::type_info & type() const
{
return maker ? maker->type() : typeid(void);
}
template<typename T>
T& cast() {
T* r = reinterpret_cast<T*>(maker);
return *r;
}
public:
PlaceMaker * maker;
};
In main I have the following:
int main() {
Types::Any a = 10;
std::cout << a.cast<int>();
}
// output: 96458224
Could anyone tell me as to where I'm going wrong?
Thanks
You're casting a Holder* to a T*. Given that Holder has virtual functions in it, that means you're gonna be looking at the vtable, not the T itself.
Related
I have a tree of polymorphic objects. I need to traverse the two trees and compare the nodes. If the nodes have different types, they are not equal. Consider this hierarchy:
struct Visitor;
struct Base {
virtual ~Base() = default;
virtual void accept(Visitor &) = 0;
};
using BasePtr = std::unique_ptr<Base>;
struct A final : Base {
void accept(Visitor &) override;
int data;
};
struct B final : Base {
void accept(Visitor &) override;
BasePtr child;
};
struct C final : Base {
void accept(Visitor &) override;
std::vector<BasePtr> children;
};
struct Visitor {
virtual void visit(const A &) = 0;
virtual void visit(const B &) = 0;
virtual void visit(const C &) = 0;
};
I know how to implement these functions:
bool equalNode(const A &, const A &);
bool equalNode(const B &, const B &);
bool equalNode(const C &, const C &);
I'm asking about how I should implement this function:
bool equalTree(const Base *, const Base *);
How do I elegantly go from equalTree to equalNode possibly using the visitor pattern?
Something like
struct RhsVisitor : public Visitor
{
bool result;
};
struct AEqualVisitor : public RhsVisitor
{
void visit(const A & rhs) override { result = equalNode(lhs, rhs); }
void visit(const B &) override { result = false; }
void visit(const C &) override { result = false; }
const A & lhs;
};
And similar for B and C
struct LhsVisitor : public Visitor
{
void visit(const A & a) override { rhsVisitor = std::make_unique<AEqualVisitor>(a); }
void visit(const B & b) override { rhsVisitor = std::make_unique<BEqualVisitor>(b); }
void visit(const C & c) override { rhsVisitor = std::make_unique<CEqualVisitor>(c); }
std::unique_ptr<RhsVisitor> rhsVisitor;
};
bool equalTree(const Base * lhs, const Base * rhs)
{
LhsVisitor vis;
lhs->accept(vis);
rhs->accept(*vis.rhsVisitor);
return vis.rhsVisitor->result;
};
There are three approaches here.
The first is - you need to do double dispatch. You have one visitor for one side and one visitor for the other side. Once you pick one side, you "save" that type as a template parameter, which you can use to visit the other side:
template <typename T>
struct Right : Visitor {
Right(T const* lhs) : lhs(lhs) { }
T const* lhs;
bool result;
void visit(A const& x) override { visit_impl(x); }
void visit(B const& x) override { visit_impl(x); }
void visit(C const& x) override { visit_impl(x); }
void visit_impl(T const& x) { result = equalNode(*lhs, x); }
template <typename U> void visit_impl(U const&) { result = false; }
};
struct Left : Visitor {
Left(Base const* lhs, Base const* rhs) : rhs(rhs) {
lhs->accept(*this);
}
Base const* rhs;
bool result;
void visit(A const& x) override { visit_impl(x); }
void visit(B const& x) override { visit_impl(x); }
void visit(C const& x) override { visit_impl(x); }
template <typename U>
void visit_impl(U const& lhs) {
Right<U> right(&lhs);
rhs->accept(right);
result = right.result;
}
};
bool equalTree(const Base *lhs, const Base *rhs) {
return Left(lhs, rhs).result;
}
The second is - you cheat. You only care about the cases where the two sides are the same type, so you only need single dispatch:
struct Eq : Vistor {
Eq(Base const* lhs, Base const* rhs) : rhs(rhs) {
lhs->accept(*this);
}
Base const* rhs;
bool result;
void visit(A const& x) override { visit_impl(x); }
void visit(B const& x) override { visit_impl(x); }
void visit(C const& x) override { visit_impl(x); }
template <typename U>
void visit_impl(U const& x) {
result = equalNode(x, *static_cast<U const*>(rhs));
}
};
bool equalTree(Base const* lhs, Base const* rhs) {
if (typeid(*lhs) == typeid(*rhs)) {
return Eq(lhs, rhs).result;
} else {
return false;
}
}
The third is - you don't do this through OO and instead use a variant:
using Element = std::variant<A, B, C>;
struct Eq {
template <typename T>
bool operator()(T const& lhs, T const& rhs) const {
return equalNode(lhs, rhs);
}
template <typename T, typename U>
bool operator()(T const&, U const&) const {
return false;
}
};
bool equalTree(Element const& lhs, Element const& rhs) {
return std::visit(Eq{}, lhs, rhs);
}
I have to pass around the void * for supporting types that can't be known at compile time, but I also don't want to go totally insane and left everything on myself so I think to use type_info for type_Checking but since type_info doesn't support copy operation I am getting compiler errors when passing them around
#include <bits/stdc++.h>
struct PropertyClassInterface {
virtual const char * name() = 0;
virtual void set(const char * property_name,std::pair<const void *,std::type_info> new_val) = 0;
virtual std::pair<std::shared_ptr<void>,std::type_info> get(const char * property_name) = 0;
template< typename Type>
static std::pair<std::shared_ptr<void>,std::type_info> get_type_pair(const Type& Value) {
std::shared_ptr<void> t = std::make_shared<Type>();
*static_cast<Type *>(t.get()) = Value;
*return std::make_pair(t,typeid(Type));* // error
}
};
struct PropertyManager {
using base_pointer = std::shared_ptr<PropertyClassInterface>;
void add_object(base_pointer new_member) {
objects.push_back(new_member);
}
template<typename Type>
void set(const char * object_name,const char * property_name,const Type& new_val) {
find_object_orThrow(object_name)->set(property_name,std::make_pair(static_cast<const void *>(&new_val),typeid(new_val)));
}
template<typename Type>
Type get(const char * object_name, const char * property_name) {
auto a = find_object_orThrow(object_name)->get(property_name);
if (typeid(Type).hash_code() != a.second.hash_code())
throw std::runtime_error{"get(): mismatched type"};
return a.first;
}
public:
std::vector<base_pointer> objects;
base_pointer find_object_orThrow(const char * obj_name){
for(auto& o : objects) {
if (!strcmpi(o->name(),obj_name)) {
return o;
}
}
throw std::runtime_error{std::string("no object named \"") + obj_name + "\" found"};
}
};
struct testClass : PropertyClassInterface {
void set(const char * property_name,std::pair<const void *,std::type_info> new_val) {
auto checkTypeInfo = [&new_val](const std::type_info& expected) {
if (new_val.second.hash_code() != expected.hash_code())
throw std::runtime_error{"set(): wrong type"};
};
if (!strcmpi(property_name,"my_number")) {
checkTypeInfo(typeid(decltype(my_number)));
my_number = *static_cast<const decltype(my_number) *>(new_val.first);
}
};
std::pair<std::shared_ptr<void>,std::type_info> get(const char * property_name) {
if (!strcmpi(property_name,"my_number")) {
PropertyClassInterface::get_type_pair(my_number);
}
}
private:
int my_number;
};
int main() {
};
so do I have to use dynamic memory for storing type_info as well
I am limited to c++11 and I know about not using bits headers and am only using for testing
What you want to do is implement an any, or use boost any.
An any isn't hard to write.
namespace details {
struct any_concept;
using pimpl=std::unique_ptr<any_concept>;
struct any_concept {
virtual ~any_concept() {}
virtua pimpl clone() const = 0;
virtual std::type_info const& type() const = 0;
private:
virtual void* unsafe_get() = 0;
virtual void const* unsafe_get() const = 0;
public:
template<class T>
T* get() {
if (typeid(T) != type()) return nullptr;
return static_cast<T*>(unsafe_get());
}
template<class T>
T const* get() const {
if (typeid(T) != type()) return nullptr;
return static_cast<T const*>(unsafe_get());
}
};
template<class T>
struct any_model:any_concept {
T t;
virtual ~any_model() = default;
virtual pimpl clone() const final override {
return pimpl( new any_model(t) );
}
virtual std::type_info const& type() const final override {
return typeid(T);
}
template<class U>
any_model(U&& u):t(std::forward<U>(u)){}
private:
virtual void* unsafe_get() final override { return std::addressof(t); }
virtual void const* unsafe_get() const final override { return std::addressof(t); }
};
}
struct any {
template<class T, typename std::enable_if<!std::is_same<any, typename std::decay<T>::type>::value, bool> =true>
any( T&& t ):
pImpl( new details::any_model<typename std::decay<T>::type>( std::forward<T>(t) ) )
{}
template<class T>
T* get() {
if (!pImpl) return nullptr;
return pImpl->get<T>();
}
template<class T>
T const* get() const {
if (!pImpl) return nullptr;
return const_cast<details::any_concept const&>(*pImpl).get<T>();
}
template<class T>
bool contains()const { return get<T>(); }
explicit operator bool() const {
return (bool)pImpl;
}
any()=default;
any(any&&)=default;
any& operator=(any&&)=default;
~any()=default;
any(any const& o):
pImpl( o.pImpl?o.pImpl->clone():pimpl{} )
{}
any& operator=(any const& o) {
any tmp(o);
std::swap(*this, tmp);
return *this;
}
private:
details::pimpl pImpl;
};
there; a really simple any implementation. Written on a phone, so probably contains typos.
It supports value semantics, but store anything (that can be copied and destroyed). If you know what it stores, you can .get<T>() it. You can ask it if it contains<T>() as well.
This is known as a vocabulary type. It is basically your void* and type info bundled in a way that makes misuse more difficult.
Consider the following class that wraps a container and type-erases its type:
class C final {
struct B {
virtual bool empty() const noexcept = 0;
};
template<class T, class A>
struct D: public B {
// several constructors aimed to
// correctly initialize the underlying container
bool empty() const noexcept override { return v.empty(); }
private:
std::vector<T, A> v;
};
// ...
public:
//...
bool operator==(const C &other) const noexcept {
// ??
// would like to compare the underlying
// container of other.b with the one
// of this->b
}
private:
// initialized somehow
B *b;
};
I'd like to add the operator== to the class C.
Internally, it should simply invoke the same operator on the underlying containers, but I'm stuck on this problem, for I don't know how to do that.
The idea is that two instances of C are equal if the operator== of their underlying containers return true.
Whatever I've tried till now, I ever ended up being unable to get the type of one of the two underlying containers, mainly the one of other.
Is there an easy solution I can't see at the moment or I should give up?
Despite the good suggestion from juanchopanza, I found that, as far as the underlying containers represent the same concept (as an example, different specializations of a vector), maybe there is no need of a type-erased iterator.
Below it's a possible implementation that relies on the operator[] and the size member method:
#include <vector>
#include <cassert>
class Clazz final {
struct BaseContainer {
virtual std::size_t size() const noexcept = 0;
virtual int operator[](std::size_t) const = 0;
virtual void push_back(int) = 0;
};
template<class Allocator>
struct Container: public BaseContainer {
Container(Allocator alloc): v{alloc} { }
std::size_t size() const noexcept override { return v.size(); }
int operator[](std::size_t pos) const override { return v[pos]; }
void push_back(int e) override { v.push_back(e); }
private:
std::vector<int, Allocator> v;
};
public:
template<class Allocator = std::allocator<int>>
Clazz(const Allocator &alloc = Allocator{})
: container{new Container<Allocator>{alloc}} { }
~Clazz() { delete container; }
void push_back(int e) { container->push_back(e); }
bool operator==(const Clazz &other) const noexcept {
const BaseContainer &cont = *container;
const BaseContainer &oCont = *(other.container);
bool ret = (cont.size() == oCont.size());
for(std::vector<int>::size_type i = 0, s = cont.size(); i < s && ret; i++) {
ret = (cont[i] == oCont[i]);
}
return ret;
}
bool operator!=(const Clazz &other) const noexcept {
return !(*this == other);
}
private:
BaseContainer *container;
};
int main() {
Clazz c1{}, c2{}, c3{};
c1.push_back(42);
c2.push_back(42);
assert(c1 == c2);
assert(c1 != c3);
}
Open to criticism, hoping this answer can help other users. :-)
Assuming you wish to return false when the comparing two different containers, this should do the job (caution: untested):
class Container
{
struct Concept
{
virtual ~Concept() = default;
virtual Concept* clone() const = 0;
virtual bool equals(Concept const*) const = 0;
};
template<typename T>
struct Model final : Concept
{
Model(T t) : data{std::move(t)} {}
Model* clone() const override { return new Model{*this}; }
virtual bool equals(Concept const* rhs) const override
{
if (typeid(*this) != typeid(*rhs))
return false;
return data == static_cast<Model const*>(rhs)->data;
}
T data;
};
std::unique_ptr<Concept> object;
public:
template<typename T>
Container(T t) : object(new Model<T>{std::move(t)}) {}
Container(Container const& that) : object{that.object->clone()} {}
Container(Container&& that) = default;
Container& operator=(Container that)
{ object = std::move(that.object); return *this; }
friend bool operator==(Container const& lhs, Container const& rhs)
{ return lhs.object->equals(rhs.object.get()); }
};
unique_ptr is quite useful. However, it is not copyable. If virutal clone (deep copy) methods are provided for its pointed class, I think it will become more useful. Is it necessary or any better way to implement it? Any similar smart pointer exist in some library? Here is a version
template<class T>
class deep_ptr: private unique_ptr<T>
{
public:
using unique_ptr<T>::operator *;
using unique_ptr<T>::operator ->;
using unique_ptr<T>::operator bool;
using unique_ptr<T>::release;
using unique_ptr<T>::reset;
using unique_ptr<T>::get;
// add (DEFAULT_CONSTRUCTOR)(MOVE_CONSTRUCTOR)(MOVE_ASSIGNMENT_METHOD) ...
explicit deep_ptr(T* p) : unique_ptr(p) {}
deep_ptr(deep_ptr const& r) : unique_ptr(r->clone()) {}
deep_ptr& operator=(deep_ptrconst& r)
{ if (this != &r) reset(r->clone()); return *this; }
};
Juse feel it is very useful but never see similar things. ???
Unless I am misunderstanding what you are looking for, if a class has a clone method, that should be sufficient to get what you are looking for.
Sample code:
#include <iostream>
#include <memory>
struct A
{
virtual ~A() {}
virtual A* clone() = 0;
};
struct B : A
{
B(int in = 0) : x(in) {}
B(B const& copy) : x(copy.x) {}
virtual ~B() {std::cout << "In B::~B()\n";}
virtual A* clone() { return new B(*this); }
int x;
};
int main()
{
std::unique_ptr<A> p1(new B(10));
std::unique_ptr<A> p2(p1->clone());
return 0;
}
Output from running the above program:
In B::~B()
In B::~B()
Without a clone method (just a copy-constructor) the following should work:
template <typename T>
class deep_ptr
{
public:
deep_ptr() : i_() {}
deep_ptr(std::nullptr_t) : i_(nullptr) {}
template <typename U>
deep_ptr(U* u) : i_(u ? new inner_impl<U>(*u) : nullptr) {}
~deep_ptr() { delete i_; }
deep_ptr(const deep_ptr& p) : i_(p.i_ ? p.i_->copy() : nullptr) {}
deep_ptr& operator=(const deep_ptr& p)
{
if (!p.i_) { i_ = nullptr; }
else { i_ = p.i_->copy(); }
}
deep_ptr(deep_ptr&& p) : i_(p.i_) { p.i_ = nullptr; }
deep_ptr& operator=(deep_ptr&& p)
{
i_ = p.i_;
p.i_ = nullptr;
}
const T* operator->() const { return get(); }
const T* get() const
{
if (i_) { return *i_; }
return nullptr;
}
const T& operator*() const { return *static_cast<T*>(*i_); }
T* operator->() { return get(); }
T* get()
{
if (i_) { return *i_; }
return nullptr;
}
T& operator*(){ return *static_cast<T*>(*i_); }
private:
struct inner
{
virtual inner* copy() const = 0;
virtual operator const T*() const = 0;
virtual operator T*() = 0;
virtual ~inner() {}
};
inner* i_;
template <typename U>
struct inner_impl : inner
{
inner_impl(const U& u) : u_(u) {}
inner_impl* copy() const override { return new inner_impl(u_); }
operator const T*() const override { return &u_; }
operator T*() override { return &u_; }
U u_;
};
};
I am trying to make a basic any type implementation in C++ (object), yet it always prints CCCCCCCC if I want to get the value from any type, and it is confusing me why (although I do know void*s are dangerous):
#include <typeinfo>
struct object
{
private:
template < typename T > struct _base
{
typedef T _ptr_type;
_ptr_type* _ptr_val()
{
return _ptr;
}
_base(_ptr_type value) : _ptr(&value){}
_base() : _ptr(nullptr){}
_ptr_type* _ptr;
};
struct _holder : _base<void*>
{
template < typename Ty > void cast(const _base<Ty>* p_base)
{
_ptr->~_ptr_type();
_ptr_type _n_type = (_ptr_type)p_base->_ptr, *_n_ptr = &_n_type;
std::swap<_ptr_type*>(_ptr, _n_ptr);
}
_holder(){}
};
public:
_holder* _h_ptr;
object() : _h_ptr(new _holder){}
template < typename T > object(const T& value) : _h_ptr(new _holder)
{
_base<T> _t_base(value);
_h_ptr->cast(&_t_base);
}
template < typename T > void operator=(const T& value)
{
_base<T> _t_base(value);
_h_ptr->cast(&_t_base);
}
const void* operator()() const
{
return *_h_ptr->_ptr_val();
}
};
#include <iostream>
int main()
{
object MyObject = 'c';
std::cout << MyObject();
getchar();
}
Perhaps my implementation of the object class will help you. It is similar to boost::any, but has a few more features (operator== and operator!=)
class object
{
private:
class dummy
{
public:
dummy()
{
}
virtual ~dummy()
{
}
virtual const std::type_info &type() const = 0;
virtual dummy *duplicate() const = 0;
virtual bool eq(object) = 0;
};
template < typename _Ty > class data : public dummy
{
public:
data()
{
}
data(const _Ty &_Value)
: __data(_Value)
{
}
~data()
{
}
const std::type_info &type() const
{
return typeid(_Ty);
}
data *duplicate() const
{
return new data<_Ty>(__data);
}
bool eq(object _Obj)
{
return _Obj.cast<_Ty>() == __data;
}
_Ty __data;
};
dummy *d;
public:
object()
{
}
template < typename _Ty > object(const _Ty &_Value)
: d(new data<_Ty>(_Value))
{
}
object(const object &_Obj)
: d(_Obj.d->duplicate())
{
}
~object()
{
if (!empty())
{
delete d;
}
}
const std::type_info &type() const
{
return (empty() ? typeid(void) : d->type());
}
object &operator=(object &_Rhs)
{
if (&_Rhs != this)
{
d = _Rhs.d->duplicate();
}
return *this;
}
object &swap(object &_Rhs)
{
std::swap(*this, _Rhs);
return *this;
}
template < typename _Ty > object &operator=(const _Ty &_Value)
{
d = new data<_Ty>(_Value);
return *this;
}
template < typename _Ty > _Ty cast() const
{
if (type() == typeid(_Ty))
{
return static_cast<data<_Ty> *>(d)->__data;
}
throw std::exception("Invalid cast type");
}
bool operator==(const object &_Rhs) const
{
return (type() == _Rhs.d->type() ? d->eq(_Rhs) : false);
}
template < typename _Ty > bool operator==(_Ty _Value) const
{
return (type() == typeid(_Ty) ? cast<_Ty>() == _Value : false);
}
bool operator!=(const object &_Rhs) const
{
return !(*this == _Rhs);
}
template < typename _Ty > bool operator!=(_Ty _Value) const
{
return !(*this == _Value);
}
bool empty() const
{
return !d;
}
};
I am afraid just like boost::any, there is no getter function, but a cast function. It can be used like this
int main()
{
object o = 5;
object o = (std::string)"Hello\n"; // doesn't like arrays, must be wrapped in a class
std::cout << o.cast<std::string>().c_str();
}
I'm sorry, but your implementation makes absolutely no sense whatsoever. It seems to be based on a completely flawed understanding of memory and the C++ object model, as well as templates. I think in your example program execution, every line of cast invokes undefined behavior, to the point where it's impossible to say what actually happens.
Throw it away and start again from scratch.
template < typename T > struct _base
{
typedef T _ptr_type;
_base(_ptr_type value) : _ptr(&value){}
_ptr_type* _ptr;
};
Well, the constructor recieves a _ptr_type by value, which means a temporary copy on the stack. _ptr(&value) makes the internal pointer point at this temporary. Then the constructor returns, and the temporary is destroyed, making this entire class broken. I'm not sure what the point of this class is yet, so I cannot make suggestions as to how to fix it.
struct _holder : _base<void*>
{
template < typename Ty > void cast(const _base<Ty>* p_base)
{
_ptr->~_ptr_type();
_ptr_type _n_type = (_ptr_type)p_base->_ptr, *_n_ptr = &_n_type;
std::swap<_ptr_type*>(_ptr, _n_ptr);
}
};
I don't know what this is for either, but the first step of your cast is to destroy the data. That's... probably a bad idea. Then you point _n_type at the data of p_base, and then make this->_ptr point at the temporary _n_type pointer which is on the stack, which means that when the function ends, this->_ptr points at invalid data again.
I have no idea how you thought this was supposed to work, so here's a rundown of the normal interface for this sort of thing:
struct object
{
private:
//base is a non-template, pure virtual interface
//used to store and access all internal data
//without knowing the actual type
struct _interface //not a template
{
virtual ~_interface () =0 {};
//clone allows us to copy without knowing the type
virtual std::unique_ptr<_interface> clone() const = 0 {}
};
//this actually stores the data
//it may be given other members, but using these
//members requires `object` to know the type
template< typename T>
struct data: _interface
{
//data() : _data() {} //default constructor - not used
//data(const data& rhs) : _data(rhs._data) {} //copy constructor - not used
//data(data&& rhs) : _data(std::move(rhs._data)) {} //move constructor - not used
data(const T& rhs) : _data(rhs) {} //value by copy
data(T&& rhs) : _data(std::move(rhs)) {} //value by move
template< typename... Us>
data(Us&&...vs) : _data(std::forward<Us>(vs)...) {} //emplace constructor
std::unique_ptr<_interface> clone() const //virtual cloning mechanism
{return std::unique_ptr<data>(new T(_data));}
T _data;
};
std::unique_ptr<_interface> _ptr;
public:
object() //default constructor
: _ptr() {}
object(const object&& rhs) //copy constructor
: _ptr(rhs ? rhs._ptr->clone() : {}) {}
object(object&& rhs) //move constructor
: _ptr(std::move(rhs._ptr)) {}
template < typename U> object(const U& _Value) //value by copy
: _ptr(new data<U>(_Value)) {}
template < typename U> object(U&& _Value) //value by move
: _ptr(new data<U>(std::move(_Value)) {}
object& operator=(const object& rhs) //copy assignment
{_ptr = rhs ? rhs._ptr->clone() : {}; return *this;}
object& operator=(object&& rhs) //move assignment
{_ptr = std::move(rhs._ptr); return *this;}
//*_ptr gives you a _interface&
//dynamic_cast<data<T>&> gives you a _data<T>& or throws a std::bad_cast
//._data gives the actual value
template< typename T> T& get()
{return dynamic_cast<data<T>&>(*_ptr)._data;}
template< typename T> const T& get() const
{return dynamic_cast<const data<T>&>(*_ptr)._data;}
explicit operator bool() const {return _ptr;} //object o; if (o) then ....
};
This only handles bare basics. Everything else is left up to you.