Boost logo

Boost Users :

Subject: Re: [Boost-users] [type_traits] Obtain type of pointer to member.
From: Nat Goodspeed (nat_at_[hidden])
Date: 2009-10-16 15:04:39


Germán Diago wrote:

> Hello. I would like to know if it's possible to obtain the base type
> from this expression:
>
> struct MyStruct {
> string field1;
> };
>
>
> decltype(&MyStruct::field1) is a pointer to member.
> I would like to obtain type string instead, removing the pointer to member.
> Is it possible?

Something like the following? I know it's clumsy... but this works in
g++ 4.0.1.

#include <iostream>
#include <string>

/*------------------------------- MemberType --*/
template <typename DEFAULT>
struct MemberType
{
     typedef void type;
};

template <class CLASS, typename TYPE>
struct MemberType<TYPE CLASS::*>
{
     typedef TYPE type;
};

template <typename T>
MemberType<T> getMemberType(const T& instance)
{
     return MemberType<T>();
}

/*----------------------------- Example Class --*/
class Example
{
public:
     Example(const std::string& value): field1(value) {}
     std::string field1;
};

int main(int argc, char *argv[])
{
     Example example("foo");
     typedef typeof(getMemberType(&Example::field1)) field1_MT;
     field1_MT::type extract(example.field1);
     std::cout << "Got " << extract << std::endl;
     return 0;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net