获取成员的类型 [英] Getting the type of a member

查看:139
本文介绍了获取成员的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有简单的方法来检索成员类型吗?

在C ++ 03中

Is there an easy way to retrieve the type of a member?
In C++03

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

int main()
{
    std::vector<Person>     people; //  get a vector of people.

    std::vector<GET_TYPE_OF(Person::age)>   ages;

    ages.push_back(people[0].age);
    ages.push_back(people[10].age);
    ages.push_back(people[13].age);

}



我实际上是这样做的(即稍微偷懒):

I am actually doing this (ie being slightly lazy):

#define BuildType(className, member, type)                                 \
        struct className ## member: TypeBase<className, type>              \
        {                                                                  \
            className ## member()                                          \
                : TypeBase<className, type>(#member, &className::member)   \
            {}                                                             \
        }

BuildType(Person, name,     std::string);
BuildType(Person, age,      int);
BuildType(Person, salary,   double);
typedef boost::mpl::vector<Personname, Personage, Personsalary> FunckyMTPMap;

但不是强制用户指定我想要编译器的成员类型实际生成它。

But rather than have to force the user to specify the type of the member I want to the compiler to generate it pragmatically.

#define BuildType(className, member)                                                  \
struct className ## member: TypeBase<className, TYPE_OF(className ## member)>         \
{                                                                                     \
   className ## member()                                                              \
      : TypeBase<className, TYPE_OF(className ## member)>(#member, &className::member)\
   {}                                                                                 \
}
BuildType(Person, name);
BuildType(Person, age);
BuildType(Person, salary);
typedef boost::mpl::vector<Personname, Personage, Personsalary> FunckyMTPMap;


推荐答案

template <class T, class M> M get_member_type(M T:: *);

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



<是C ++ 11的方式。它要求您使用& Person :: age 而不是 Person :: age ,虽然您可以轻松调整宏来使&符隐式。

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.

这篇关于获取成员的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆