Getting the type of a member

江枫思渺然 提交于 2019-12-04 01:00:08
template <class T, class M> M get_member_type(M T:: *);

#define GET_TYPE_OF(mem) decltype(get_member_type(mem))

Is the C++11 way. It requires you to use &Person::age instead of Person::age, although you could easily adjust the macro to make the ampersand implicit.

Dietmar Kühl

In C++2003 it can't be done directly but you can delegate to a function template which deduces the type:

template <typename T, typename S>
void deduce_member_type(T S::* member) {
     ...
}

int main() {
    deduce_member_type(&Person::age);
}

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<BOOST_TYPEOF(Person::age) > ages;

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

#include <typeinfo>
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;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!