c++ - How to print a vector of boost::any, when i have the element types stored in another vector of strings? -
this question has answer here:
- how print boost::any stream? 8 answers
- i'm using vector of boost::any store different data types, construct symbol table given program file.
- i'm storing datatypes in separate vector strings.
- while trying print boost::any using boost::any_cast<>(), if pass data type stored string cast type, bad_any_cast error.
how overcome hurdle , print vector type info have strings.
vector<boost::any> vany; vector<string> vtype; string vartype; vany.push_back(10); vtype.push_back("int"); vany.push_back(2.5); vtype.push_back("float"); vany.push_back("hello"); vtype.push_back("string"); for(int i=0; i<3; i++) { vartype = vtype[i]; cout<<boost::any_cast<vartype>(vany[i]); //this doesn't work, how make work? }
c++ statically typed language. every expression must have type know @ compile time.
the value of string (or non-constexpr variable) defined @ runtime. such, cannot perform cast type named string.
any useful if know type stored in particular value. , must know @ compile time, not runtime. it's hiding data type between person giving out value , person receiving it. isn't allowed break c++'s static typing rules.
there no generalized solution being able store type in array , performing arbitrary operations on them. develop type any, able use polymorphic access actual type invoke operator<< on value. cannot outside of any.
Comments
Post a Comment