• Advertisement
Sign in to follow this  

boost library type to normal C++

This topic is 2236 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How can I convert boost library defined any_cast function to normal C++ types.
I don't want to use Boost library.

T val
val = boost::any_cast<T>(attributes->value);


Please help.

Share this post


Link to post
Share on other sites
Advertisement
Here's a hastily written, un-tested, non-feature-complete implementation that has received no performance tuning at all. Use at your own risk.


#include <algorithm> // swap
#include <typeinfo> // bad_cast.
#include <iostream>

namespace impl
{
struct any_vtable
{
void *(*clone)(const void *);
void (*destroy)(void *);
void (*throw_ptr)(void *);
};

template<typename T>
struct any_traits
{
static void *clone(const void *obj) { return new T(*static_cast<const T *>(obj)); }
static void destroy(void *obj) { delete static_cast<T *>(obj); }
static void throw_ptr(void *obj) { throw static_cast<T *>(obj); }
static any_vtable vtable;
};

template<typename T>
any_vtable any_traits<T>::vtable = { &any_traits<T>::clone, &any_traits<T>::destroy, &any_traits<T>::throw_ptr };

} // impl

class any
{
public:
template<typename T>
explicit any(const T &obj) : vt(&impl::any_traits<T>::vtable), p(new T(obj)) { }

~any() { vt->destroy(p); }
any(const any &rhs) : vt(rhs.vt), p(vt->clone(rhs.p)) { }
any &operator= (const any &rhs) { any temp(rhs); std::swap(p, temp.p); std::swap(vt, temp.vt); return *this; }

template<typename To>
To &cast()
{
try { vt->throw_ptr(p); }
catch (To *ex) { return *ex; }
catch (...) { }
throw std::bad_cast();
}

private:
const impl::any_vtable *vt;
void *p;
};

int main()
{
any test(std::string("hello"));
std::cout << test.cast<std::string>() << '\n';

try { std::cout << test.cast<int>() << '\n'; }
catch (...) { std::cout << "not an int\n"; }

return 0;
}


EDIT: I've edited this a few times now, but I've just spotted/fixed another bug in the assignment operator because I was trying to by overly-succint for the sake of a forum post. It really is best to use boost::any.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement