I recently started to use Boost
C++ library and I am testing the any
class which can hold any data type. Actually I am trying to define the operator<<
to print easily the content of any variable of type any
(and sure, the class of the content should have the operator<<
defined too).
I only started by sample types ( int
, double
...) because they have be displayed by default. And till now, I have this code :
#include <boost/any.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace boost;
ostream& operator<<(ostream& out, any& a){
if(a.type() == typeid(int))
out << any_cast<int>(a);
else if(a.type() == typeid(double))
out << any_cast<double>(a);
// else ...
// But what about other types/classes ?!
}
int main(){
any a = 5;
cout << a << endl;
}
So the problem here is that I have to enumerate all possible types. Is there any way to cast the variable to a particular type
having the type_info
of this particular type
?