Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ typename of member variable

Is it possible to get typename of a member variable? For example:

struct C { int value ; };

typedef typeof(C::value) type; // something like that?

Thanks

like image 225
Anycorn Avatar asked Mar 19 '10 01:03

Anycorn


3 Answers

Not in C++03. C++0x introduces decltype:

typedef decltype(C::value) type;

Some compilers have a typeof extension, though:

typedef typeof(C::value) type; // gcc

If you're okay with Boost, they have a library for it:

typedef BOOST_TYPEOF(C::value) type;
like image 128
GManNickG Avatar answered Sep 23 '22 02:09

GManNickG


Only if you are fine with processing the type in a function

struct C { int value ; };

template<typename T, typename C>
void process(T C::*) {
  /* T is int */
}

int main() {
  process(&C::value); 
}

It won't work with reference data members. C++0x will allow decltype(C::value) to do that more easily. Not only that, but it allows decltype(C::value + 5) and any other fancy expression stuff within the decltype. Gcc4.5 already supports it.

like image 29
Johannes Schaub - litb Avatar answered Sep 23 '22 02:09

Johannes Schaub - litb


May not be exactly what you're looking for, but a possibly better solution in the long run:

struct C {
  typedef int type;
  type value;
};

// now we can access the type of C::value as C::type
typedef C::type type;

This isn't exactly what you want, but it does allow us to hide the implementation type of C::value so that we can later change it, which is what I suspect you're after.

like image 26
Chris Lutz Avatar answered Sep 26 '22 02:09

Chris Lutz