相关文章推荐
天涯  ·  MacBook Pro ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am looking for a way to check boost::any data type. If i assign an int to boost::any like:

boost::any num1 = 5;

And then use typeid(num1).name() , i want my output to be "int" so that i can use it in a if else statement in the future. However for some reason it keeps giving me this as the data type: N5boost3anyE

#include <typeinfo>
#include <iostream>
#include <boost/any.hpp>
using namespace std;
int main()
    int     a;
    double  b;
    float   c;
    bool    d;
    int16_t e;
    int32_t f;
    cout << "     int: " << typeid(a).name() << endl;
    cout << "sizeof(): " << sizeof(a) << endl << endl;
    cout << "  double: " << typeid(b).name() << endl;
    cout << "sizeof(): " << sizeof(b) << endl << endl;
    cout << "   float: " << typeid(c).name() << endl;
    cout << "sizeof(): " << sizeof(c) << endl << endl;
    cout << "    bool: " << typeid(d).name() << endl;
    cout << "sizeof(): " << sizeof(d) << endl << endl;
    cout << " int16_t: " << typeid(e).name() << endl;
    cout << "sizeof(): " << sizeof(e) << endl << endl;
    cout << " int32_t: " << typeid(f).name() << endl;
    cout << "sizeof(): " << sizeof(f) << endl << endl;
    boost::any num1 = 5;
    cout << "typeid(num1).name(): " << typeid(num1).name() << endl;
    boost::any num2 = "dog";
    cout << "typeid(num2).name(): " << typeid(num2).name() << endl;

Output:

johns-Air:cpp jdoe$ ./main 
int: i
sizeof(): 4
double: d
sizeof(): 8
float: f
sizeof(): 4
    bool: b
sizeof(): 1
int16_t: s
sizeof(): 2
int32_t: i
sizeof(): 4
typeid(num1).name(): N5boost3anyE
typeid(num2).name(): N5boost3anyE
                You don't need this for an if-else. It's expected to use any_cast to (try to) cast back to the actual type. Given that you're trying more than one, there's a chance that boost::variant is more suitable.
– chris
                Mar 18, 2022 at 2:21

You need to use boost::any's member function type() which returns a const std::type_info& of the contained value

cout << "num1.type().name(): " << num1.type().name() << endl;
                method boost::any::type::name don't return name clearly which is mangled.To demangle refer this stackoverflow.com/questions/4465872/…
– long.kl
                Mar 18, 2022 at 2:52
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.