C ++ typename member variable

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

struct C { int value ; }; typedef typeof(C::value) type; // something like that? 

thanks

+4
source share
4 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 ok with Boost, they have a library :

 typedef BOOST_TYPEOF(C::value) type; 
+4
source

Only if you are fine with type handling in a function

 struct C { int value ; }; template<typename T, typename C> void process(TC::*) { /* T is int */ } int main() { process(&C::value); } 

It will not work with reference data. C ++ 0x will allow decltype(C::value) to do this more easily. Not only that, but decltype(C::value + 5) and any other fancy expressions in decltype . Gcc4.5 already supports it.

+4
source

It may not be exactly what you are looking for, but perhaps the best 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 is not exactly what you want, but it allows us to hide the implementation type of C::value so that we can subsequently change it, which I suspect you need.

+1
source

It depends on what you need to do, but you would do something like:

 #include <iostream> using namespace std; struct C { typedef int VType; VType value; }; int main() { C::VType a = 3; cout << a << endl; } 
0
source

Source: https://habr.com/ru/post/1304531/


All Articles