The var class holds a pointer to the inner_base class. Concrete implementations on inner (such as inner<int> or inner<std::string>) inherit from inner_base. The var representation will access the concrete implementations through the generic inner_base interface. To hold arbitrary types of data a little more scaffolding is needed:

Here the var class forwards calls of Type() to it's inner_base interface which is overridden by the concrete inner<_Ty> subclass which ultimately returns the underlying type. This technique of forwarding accessor methods to a virtual interface which is overridden by concrete implementations is expanded for a fully useful generic type.

structvar{var():_inner(newinner<int>(0)){}//default construct to an integervar(constvar&src):_inner(src._inner->clone()){}//copy constructor calls clone method of concrete typetemplate<typename_Ty>var(_Tysrc):_inner(newinner<_Ty>(std::forward<_Ty>(src))){}template<typename_Ty>var&operator=(_Tysrc){//assign to a concrete type_inner=std::make_unique<inner<_Ty>>(std::forward<_Ty>(src));return*this;}var&operator=(constvar&src){//assign to another var typevaroTmp(src);std::swap(oTmp,*this);return*this;}//interrogate the underlying type through the inner_base interfaceconststd::type_info&Type()const{return_inner->Type();}boolIsPOD()const{return_inner->IsPOD();}size_tSize()const{return_inner->Size();}//cast the underlying type at run-timetemplate<typename_Ty>_Ty&cast(){return*dynamic_cast<inner<_Ty>&>(*_inner);}template<typename_Ty>const_Ty&cast()const{return*dynamic_cast<inner<_Ty>&>(*_inner);}structinner_base{usingPointer=std::unique_ptr<inner_base>;virtual~inner_base(){}virtualinner_base*clone()const=0;virtualconststd::type_info&Type()const=0;virtualboolIsPOD()const=0;virtualsize_tSize()const=0;};template<typename_Ty>structinner:inner_base{inner(_Tynewval):_value(std::move(newval)){}virtualinner_base*clone()constoverride{returnnewinner(_value);}virtualconststd::type_info&Type()constoverride{returntypeid(_Ty);}_Ty&operator*(){return_value;}const_Ty&operator*()const{return_value;}virtualboolIsPOD()const{returnstd::is_pod<_Ty>::value;}virtualsize_tSize()const{returnsizeof(_Ty);}private:_Ty_value;};inner_base::Pointer_inner;};//this is a specialization of an erased std::wstringtemplate<>structvar::inner<std::wstring>:var::inner_base{inner(std::wstringnewval):_value(std::move(newval)){}virtualinner_base*clone()constoverride{returnnewinner(_value);}virtualconststd::type_info&Type()constoverride{returntypeid(std::wstring);}std::wstring&operator*(){return_value;}conststd::wstring&operator*()const{return_value;}virtualboolIsPOD()const{returnfalse;}virtualsize_tSize()const{return_value.size();}private:std::wstring_value;};