NOTE: This question was originally asked way back in 2012. Before the decltype
specifier was fully implemented by any major compilers. You should not be looking at this code unless you only have access to C++03. All major C++11 compliant compilers now support decltype
.
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;