Getting the type of a member

前端 未结 3 1493
鱼传尺愫
鱼传尺愫 2021-01-04 02:24

NOTE: This question was originally asked way back in 2012. Before the decltype specifier was fully implemented by any major compilers. You shou

3条回答
  •  醉酒成梦
    2021-01-04 02:58

    Since in your examples you use boost I'd use TYPEOF from boost.

    http://www.boost.org/doc/libs/1_35_0/doc/html/typeof.html

    it works very similarly to decltype of C++11.

    http://en.wikipedia.org/wiki/C%2B%2B11#Type_inference in your case:

    std::vector ages;
    

    you can compare the types decltype or BOOST_TYPEOF gives you with typeinfo

    #include 
    cout << typeid(obj).name() << endl;
    

    you need to make a proper people vector with length >14 for the example to work.

    gcc has typeof or typeof doing the same thing.

    As a side note. For the example you gave you could just define the types in the struct instead if none of the above is relevant for you.

    struct Person
    {
      typedef  int agetype;
      std::string name;
      agetype         age;
      int         salary;
    };
    

    then use std::vector< Person::agetype > ages;

提交回复
热议问题