
AMDG On 06/18/2012 12:25 PM, lcaminiti wrote:
lcaminiti wrote
I will use the lib in some use cases that I ran into the past and let you know if I find a nice example not too complex (I don't remember what the use cases were but they were about type erasure).
Is this a sensible use of this library or is there a much better way to do the following?
This is a textbook use case for the library. Use TypeErasure states the intent of the code clearly. obj_ can hold any type that is CopyConstructible, and Ostreamable. (you don't actually need typeid_ here).
#include <boost/type_erasure/any.hpp> #include <boost/type_erasure/builtin.hpp> #include <boost/type_erasure/operators.hpp> #include <boost/mpl/vector.hpp> #include <iostream>
struct display { public: template< typename T > explicit display ( T const& obj ) : obj_(obj) {}
public: void print ( void ) { std::cout << obj_ << std::endl; }
public: boost::type_erasure::any< boost::mpl::vector< boost::type_erasure::copy_constructible<> , boost::type_erasure::typeid_<> , boost::type_erasure::ostreamable<> > > obj_; };
int main ( void ) { display i(-1), d('x'); i.print(); d.print(); return 0; }
I had to do something like this in the past where: 1. I didn't want display to be a template but I wanted it to handle generic types as passed to the constructor. 2. I knew a-priori the operations that display needed from T (e.g., operator<<). 3. I had to store the object of the generic type T so the operation on T could be performed later (e.g., by print). I needed to do this as an implementation detail so the original problem I was trying to solve has little relevance in general. But I wanted to ask if using this library is a reasonable approach to do the above of it there are better ways.
In Christ, Steven Watanabe